Example #1
0
        /// <summary>
        /// Gets all attributes for the entity with the specified id
        /// </summary>
        /// <returns>The response object</returns>
        public async Task <ContextResponse> GetAttributesForEntityAsync(string entityId)
        {
            RESTClient <ContextResponse> client = new RESTClient <ContextResponse>(OrionConfig.AuthHeaderKey, _config.Token);
            string uri = string.Format(OrionConfig.ConvenienceUrlFormatOneParam, _config.BaseUrl, _config.Version1Path, OrionConfig.ContextEntitiesPath, entityId, OrionConfig.AttributesPath);

            return(await client.GetAsync(uri));
        }
Example #2
0
        /// <summary>
        /// Deletes the value of the specified attribute and entity id
        /// </summary>
        /// <returns>The response object</returns>
        public async Task <StatusCode> DeleteAttributeForEntityAsync(string entityId, string attributeName)
        {
            RESTClient <StatusCode> client = new RESTClient <StatusCode>(OrionConfig.AuthHeaderKey, _config.Token);
            string uri = string.Format(OrionConfig.ConvenienceUrlFormatTwoParams, _config.BaseUrl, _config.Version1Path, OrionConfig.ContextEntitiesPath, entityId, OrionConfig.AttributesPath, attributeName);

            return(await client.DeleteAsync(uri));
        }
Example #3
0
        /// <summary>
        /// Deletes the entity with the specified id
        /// </summary>
        /// <returns>The response object</returns>
        public async Task <ContextResponse> DeleteEntityAsync(string entityId)
        {
            RESTClient <ContextResponse> client = new RESTClient <ContextResponse>(OrionConfig.AuthHeaderKey, _config.Token);
            string uri = string.Format(OrionConfig.ConvenienceUrlFormat, _config.BaseUrl, _config.Version1Path, OrionConfig.ContextEntitiesPath, entityId);

            return(await client.DeleteAsync(uri));
        }
Example #4
0
        /// <summary>
        /// Gets all types currently in the Orion Context Broker
        /// </summary>
        /// <returns>The response object</returns>
        public async Task <ContextAttributesResponse> GetAttributesForTypeAsync(string type)
        {
            RESTClient <ContextAttributesResponse> client = new RESTClient <ContextAttributesResponse>(OrionConfig.AuthHeaderKey, _config.Token);
            string uri = string.Format(OrionConfig.ConvenienceUrlFormat, _config.BaseUrl, _config.Version1Path, OrionConfig.ContextTypesPath, type);

            return(await client.GetAsync(uri));
        }
        // private class FactAttribute : Attribute { } // Comment out this line to run this test

        async public Task <GTXClient> InitTest()
        {
            var rest = new RESTClient("http://localhost:7740/");
            await rest.InitializeBRIDFromChainID(0);

            return(new GTXClient(rest));
        }
Example #6
0
        /// <summary>
        /// Gets the current version of the Orion Context Broker
        /// </summary>
        /// <returns>The version object</returns>
        public async Task <OrionVersion> GetOrionVersionAsync()
        {
            RESTClient <OrionVersion> client = new RESTClient <OrionVersion>(OrionConfig.AuthHeaderKey, _config.Token);
            string uri = string.Format(OrionConfig.VersionUrlFormat, _config.BaseUrl, OrionConfig.VersionPath);

            return(await client.GetAsync(uri));
        }
Example #7
0
        static void Main(string[] args)
        {
            if (args.Length > 0)
            {
                RESTClient rESTClient;
                rESTClient = new RESTClient(args[0]);

                string file1;
                file1 = rESTClient.GetFileName(1);

                string file2;
                file2 = rESTClient.GetFileName(2);

                string ffile1;
                ffile1 = file1;

                int val1;
                val1 = rESTClient.HandleFile(ffile1);

                string ffile2;
                ffile2 = file2;

                int val2;
                val2 = rESTClient.HandleFile(ffile2);

                int vval1, vval2;

                vval1 = val1;
                vval2 = val2;
                Debug.Assert(rESTClient.count == vval1 + vval2);
            }
        }
Example #8
0
        public async Task GetAll_ReturnsNull_WhenNotValid()
        {
            var client = new RESTClient("https://jsonplaceholder.typicode.com");
            var posts  = await client.GetAll <BlogPost>("invalid_posts");

            Assert.Null(posts);
        }
Example #9
0
    public APIOutput ProblemStatus(bool ignoreCertificate = false)
    {
        // Creating Variables
        RESTClient APIClient   = new RESTClient(Target);
        APIOutput  outputValue = new APIOutput();
        Dictionary <string, string> parameters = new Dictionary <string, string>
        {
            // Adding Parameters
            { "Api-Token", Token }
        };
        // API Call
        string APIResponse = APIClient.GetRequest("/problem/status", URLParameters: parameters, IgnoreCertificate: ignoreCertificate);

        outputValue.RawData = APIResponse;
        // Processing Response
        if (APIResponse == "Certificate Error")
        {
            outputValue.APIStatus = APIResult.CertificateError;
        }
        else
        {
            outputValue.APIStatus   = APIResult.Success;
            outputValue.OutputClass = JsonConvert.DeserializeObject <ProblemData.ProblemStatus.Root_Problemstatus>(APIResponse);
        }
        return(outputValue);
    }
        public async Task <ActionResult> UpdateInformacoesParaPagamento(InformacoesParaPagamentoInputModel model)
        {
            if (ModelState.IsValid)
            {
                Session["UpdateInformacoesParaPagamento"] = model;

                try
                {
                    var Id           = (int)Session["UpdateId"];
                    var candidatoDTO = new CandidatoDTO(
                        (InformacoesDeContatoInputModel)Session["UpdateInformacoesDeContato"],
                        (PreferenciasDeTrabalhoInputModel)Session["UpdatePreferenciasDeTrabalho"],
                        (QuestionarioDeHabilidadesInputModel)Session["UpdateQuestionarioDeHabilidades"],
                        (InformacoesParaPagamentoInputModel)Session["UpdateInformacoesParaPagamento"]
                        );

                    RESTClient client = new RESTClient(baseUrl);
                    await client.PutJson <string>($"api/Candidato/{Id}", candidatoDTO);

                    ClearUpdateCandidatoSession();

                    return(View("UpdateConcluido", Id));
                }
                catch
                {
                    return(View(model));
                }
            }
            else
            {
                return(View(model));
            }
        }
Example #11
0
        public APIException createException(RESTClient client)
        {
            APIException         resultException = null;
            ExceptionDescription exceptionDesc   = null;

            try
            {
                var responseInJSON = JObject.Parse(client.RawResponse);
                var status         = responseInJSON.Value <string>(DefaultAPIResponseValidator.FIELD_STATUS);
                if (status != null && status == DefaultAPIResponseValidator.STATUS_ERROR)
                {
                    var result = responseInJSON.Value <JObject>(APIMethod.FIELD_RESULT);
                    if (result != null)
                    {
                        exceptionDesc   = result.ToObject <ExceptionDescription>();
                        resultException = createException(exceptionDesc.Exception, client, exceptionDesc.ErrorMessage, exceptionDesc.Name);
                    }
                }
                if (resultException == null)
                {
                    resultException = new APIException(client, (exceptionDesc != null ? exceptionDesc.ErrorMessage : ""));
                }
            }
            catch (Newtonsoft.Json.JsonReaderException)
            {
                resultException = new APIException(client, "Invalid json with error description");
            }
            return(resultException);
        }
Example #12
0
        public string SendSmsVerificationCode(string phone)
        {
            string apiPath = $"utils/phone/sms/{phone}/4";
            string result  = new RESTClient().PostRequest(_baseApiUrl + apiPath);

            return(JsonConvert.DeserializeObject <SmsVerificationCode>(result).Code);
        }
        private async void UpdateClick(object sender, EventArgs e)
        {
            if (ValidateData())
            {
                user.username = etUsername.Text.ToString().Trim();
                user.password = etPassword.Text.ToString().Trim();
                user.phoneno  = etPhone.Text.ToString().Trim();
                user.gender   = spnGender.SelectedItem.ToString();
                progress.SetMessage("Updating Account.....");
                RunOnUiThread(() =>
                {
                    progress.Show();
                });
                await RESTClient.UpdateMemberAsync(this, user);

                GetSharedPreferences(GetString(Resource.String.PreferenceFileName), FileCreationMode.Private)
                .Edit()
                .PutString(GetString(Resource.String.PreferenceSavedMember), JsonConvert.SerializeObject(user))
                .Commit();
                RunOnUiThread(() =>
                {
                    progress.Dismiss();
                });
            }
        }
Example #14
0
        private void DeletedSignUp(SignUpInfo signUpInfo)
        {
            SignUpControl oneSignUpItem = null;

            for (int loop = 0; loop < signUpList.Children.Count; loop++)
            {
                if (signUpList.Children[loop].GetType().ToString() == "SignInApp.SignUpControl")
                {
                    oneSignUpItem = signUpList.Children[loop] as SignUpControl;
                    if (oneSignUpItem.mSignUpInfo.Id == signUpInfo.Id)
                    {
                        //删除
                        string outMessage = "";
                        string response   = RESTClient.SignOut(signUpInfo.Id, ref outMessage);
                        if (response == null || response == "")
                        {
                            if (outMessage == "")
                            {
                                outMessage = "删除签到失败,服务器错误";
                            }
                            broder_back.Visibility = Visibility.Collapsed;
                            _loading.Visibility    = Visibility.Collapsed;
                            WarningTipWindow tipDialog = new WarningTipWindow(outMessage);
                            tipDialog.ShowDialog();
                            return;
                        }

                        try
                        {
                            JObject jResp  = (JObject)JsonConvert.DeserializeObject(response);
                            String  status = (String)jResp.SelectToken("status", true);
                            if (status != "success")
                            {
                                string message = (String)jResp.SelectToken("message", true);
                                broder_back.Visibility = Visibility.Collapsed;
                                _loading.Visibility    = Visibility.Collapsed;
                                WarningTipWindow tipDialog = new WarningTipWindow("删除签到失败:" + message);
                                tipDialog.ShowDialog();
                                LogHelper.WriteWarnLog("删除签到失败:" + message);
                                return;
                            }

                            LogHelper.WriteInfoLog("查询签到成功");
                            broder_back.Visibility = Visibility.Collapsed;
                            _loading.Visibility    = Visibility.Collapsed;
                            signUpList.Children.RemoveAt(loop);
                            return;
                        }
                        catch (Exception err)
                        {
                            broder_back.Visibility = Visibility.Collapsed;
                            _loading.Visibility    = Visibility.Collapsed;
                            WarningTipWindow tipDialog = new WarningTipWindow("查询签到失败," + err.Message);
                            tipDialog.ShowDialog();
                            return;
                        }
                    }
                }
            }
        }
Example #15
0
        private void ExitSystemClickHandler(object sender, RoutedEventArgs e)
        {
            string outMessage = "";

            RESTClient.Logout(ref outMessage);
            this.Close();
        }
Example #16
0
        public void Execute(IJobExecutionContext context)
        {
            var name = context.JobDetail.JobDataMap.Get(JobDataMapKeys.Name);

            Logger.Info(string.Format("Job : {0} : {1} : {2} : Executing", this.GetType().Name, name, Id));

            foreach (var ep in CustomConfig.Instance.EndPoints)
            {
                var endPoint = ep;
                var request  = new DipsTransportRequest {
                    Id = this.Id, Message = "Process Dips Files Transfer"
                };

                var thread = new Thread(() =>
                {
                    Logger.Info(string.Format("Job : {0} : {1} : {2} : Dispatching Request, EndPoint = {3}, Data = {4}", Id, this.GetType().Name, name, endPoint.Url, request.ToJson()));

                    Thread.CurrentThread.IsBackground = true;

                    var response = new RESTClient()
                                   .TryPost <DipsTransportRequest, DipsTransportResponse>(endPoint.Url, request)
                                   .Result;

                    Logger.Info(string.Format("Job : {0} : {1} : {2} : Response Received, EndPoint = {3}, Data = {4}", Id, this.GetType().Name, name, endPoint.Url, response.ToJson()));
                }
                                        );

                thread.Start();
            }

            Logger.Info(string.Format("Job : {0} : {1} : {2} : Completed", this.GetType().Name, name, Id));
        }
Example #17
0
        public override async Task <BlockChainAddressInformation> GetAddress(string address)
        {
            try
            {
                await _SemaphoreSlim.WaitAsync();

                //https://chain.so/api#rate-limits
                //5 requests/second * 3
                await Task.Delay(400);

                var balance = await RESTClient.GetAsync <ChainSoAddress>($"/api/v2/get_address_balance/{Currency}/{address}");

                if (balance.data.confirmed_balance != 0)
                {
                    //TODO: This should include both confirmed and unconformed...
                    return(new BlockChainAddressInformation(address, balance.data.confirmed_balance, false));
                }

                //There is no balance so check to see if the address was ever used
                await Task.Delay(400);

                var received = await RESTClient.GetAsync <ChainSoAddressReceived>($"/api/v2/get_address_received/{Currency}/{address}");

                return(new BlockChainAddressInformation(address, balance.data.confirmed_balance, received.data.confirmed_received_value == 0));
            }
            finally
            {
                _SemaphoreSlim.Release();
            }
        }
        private void upPlay_Click(object sender, RoutedEventArgs e)
        {
            List <Record> recordList = new List <Record>();

            if (playlistView.Items.Count == 0)
            {
                recordList.Add(new Record()
                {
                    UID = int.Parse(MainPage.userSettings._userID), videoname = "#####"
                });
            }
            else
            {
                foreach (MediaModel mediaModel in playlistView.Items)
                {
                    if (mediaModel.canSync)
                    {
                        Record record = new Record()
                        {
                            bytes      = 123,
                            UID        = int.Parse(MainPage.userSettings._userID),
                            videoname  = mediaModel.Title,
                            LastOpened = DateTime.Now.ToString(),
                            location   = "LibraryVideo",
                            record     = mediaModel.PlaybackPosition.ToString()
                        };
                        recordList.Add(record);
                    }
                }
            }

            RESTClient.UpdateRecordList(recordList);
        }
Example #19
0
        public IAsyncResult BeginPost(string classname, object pobject, ProtoAPIPostCallback callback)
        {
            if (string.IsNullOrEmpty(classname) || null == pobject)
            {
                throw new ProtoAPIException("Invalid parameters: AsyncGet cannot be completed");
            }

            CheckUserAndAppKey();

            ResponseStatus <string> response_status = new ResponseStatus <string>();
            ManualResetEvent        finished_event  = new ManualResetEvent(false);
            RESTAsyncResult         async_result    = new RESTAsyncResult(finished_event, response_status);

            string payload = null;

            try{
                payload = JsonConvert.SerializeObject(pobject, new IsoDateTimeConverter());
            } catch (Exception e) {
                throw new ProtoAPIException("Unable to serialize object to json: " + e.Message);
            }
            if (string.IsNullOrEmpty(payload))
            {
                throw new ProtoAPIException("Resulting json string is null or empty");
            }

            RESTClient client = new RESTClient(m_ServiceUri);

            client.SetBasicAuthorizationCredential(m_username, m_appkey);

            client.AsyncPost("objects/" + classname, null, payload, delegate(int status, string response){
                response_status.statusCode = status;

                if (status == 201)
                {
                    JsonResponseObject <string> data_wrapper;
                    data_wrapper = JsonConvert.DeserializeObject <JsonResponseObject <string> >(response, new IsoDateTimeConverter());

                    response_status.responseData = data_wrapper.data;

                    if (null != callback)
                    {
                        callback(response_status, data_wrapper.data as string);
                    }
                }
                else
                {
                    response_status.responseData = response;
                    response_status.errorMessage = response;

                    if (null != callback)
                    {
                        callback(response_status, null);
                    }
                }

                async_result.SetCompleted();
            });

            return(async_result);
        }
Example #20
0
        public override async Task <Collection <ExchangePairPrice> > GetPairs(CurrencySymbol baseSymbol, PriceType priceType)
        {
            var retVal  = new Collection <ExchangePairPrice>();
            var markets = await RESTClient.GetAsync <Markets>("/api/v1.1/public/getmarketsummaries");

            foreach (var pair in markets.result)
            {
                var baseSymbolName = pair.MarketName.Substring(0, 3);
                var toSymbolName   = pair.MarketName.Substring(4, pair.MarketName.Length - 4);

                var currentBaseSymbol = new CurrencySymbol(baseSymbolName);

                if (baseSymbol != null)
                {
                    if (!currentBaseSymbol.Equals(baseSymbol))
                    {
                        continue;
                    }
                }

                retVal.Add(new ExchangePairPrice(pair.Volume)
                {
                    BaseSymbol = currentBaseSymbol, ToSymbol = new CurrencySymbol(toSymbolName), Price = priceType == PriceType.Ask ? pair.Ask : pair.Bid
                });
            }

            return(retVal);
        }
Example #21
0
 public void Start()
 {
     if (!RESTClient.IsInitialized)
     {
         RESTClient.Init(OnInitialized);
     }
 }
        public void UpdatePartial()
        {
            using (MSSQLDbClient sqlClient = new MSSQLDbClient(ConnectionString))
            {
                ProductRowApiO existing = sqlClient.Fill <ProductRowApiO>(GetRecordSql);

                if (existing == null)
                {
                    this.Create();
                    existing = sqlClient.Fill <ProductRowApiO>(GetRecordSql);
                }

                Assert.NotNull(existing);

                using (RESTClient restClient = new RESTClient(BaseUrl))
                {
                    string partialJson = "{ \"ProductId\": " + existing.ProductId + ", \"CategoryId\": 2, \"SupplierId\": 1, \"UnitPrice\": 32.1 }";
                    RestResult <ProductRowApiO> apiResult = restClient.Execute <ProductRowApiO>("Product", RestSharp.Method.PATCH, jsonBodyPartial: partialJson, headerParameters: Headers);
                    Assert.True(apiResult.StatusCode == 200, apiResult.Content);

                    ProductRowApiO dbValue = sqlClient.Fill <ProductRowApiO>(GetRecordSql);
                    Assert.True(dbValue.UnitPrice == (decimal)32.1, "Incorrect text was saved.");
                }
            }
        }
        public void Update()
        {
            using (MSSQLDbClient sqlClient = new MSSQLDbClient(ConnectionString))
            {
                ProductRowApiO existing = sqlClient.Fill <ProductRowApiO>(GetRecordSql);

                if (existing == null)
                {
                    this.Create();
                    existing = sqlClient.Fill <ProductRowApiO>(GetRecordSql);
                }

                Assert.NotNull(existing);

                using (RESTClient restClient = new RESTClient(BaseUrl))
                {
                    ProductRowApiO updated = existing;
                    updated.UnitPrice = 123;

                    RestResult <ProductRowApiO> apiResult = restClient.Execute <ProductRowApiO>("Product", RestSharp.Method.PATCH, jsonBody: updated, headerParameters: Headers);
                    Assert.True(apiResult.StatusCode == 200, apiResult.Content);
                    Assert.True(apiResult.Result.UnitPrice == 123, "The updated value was not returned");
                }

                ProductRowApiO dbValue = sqlClient.Fill <ProductRowApiO>(GetRecordSql);
                Assert.True(dbValue.UnitPrice == 123, "The updated value was not returned");
            }
        }
        public void UpdatePartialBadly()
        {
            using (MSSQLDbClient sqlClient = new MSSQLDbClient(ConnectionString))
            {
                ProductRowApiO existingCategory = sqlClient.Fill <ProductRowApiO>(GetRecordSql);

                if (existingCategory == null)
                {
                    this.Create();
                    existingCategory = sqlClient.Fill <ProductRowApiO>(GetRecordSql);
                }

                Assert.NotNull(existingCategory);

                using (RESTClient restClient = new RESTClient(BaseUrl))
                {
                    string partialJson = "{ \"ProductId\": " + existingCategory.ProductId + " }";
                    RestResult <ProductRowApiO> apiResult = restClient.Execute <ProductRowApiO>("Product", RestSharp.Method.PATCH, jsonBodyPartial: partialJson, headerParameters: Headers);

                    Assert.False(apiResult.StatusCode == 200, apiResult.Content);
                }

                ProductRowApiO dbValue = sqlClient.Fill <ProductRowApiO>(GetRecordSql);
                Assert.False(dbValue.ProductName == string.Empty, "Incorrect text was saved.");
            }
        }
        public void Delete()
        {
            using (MSSQLDbClient sqlClient = new MSSQLDbClient(ConnectionString))
            {
                ProductRowApiO existingCategory = sqlClient.Fill <ProductRowApiO>(GetRecordSql);

                if (existingCategory == null)
                {
                    this.Create();
                    existingCategory = sqlClient.Fill <ProductRowApiO>(GetRecordSql);
                }

                Assert.NotNull(existingCategory);

                using (RESTClient restClient = new RESTClient(BaseUrl))
                {
                    List <KeyValuePair <string, string> > routeParams = new List <KeyValuePair <string, string> >
                    {
                        new KeyValuePair <string, string>("key", existingCategory.ProductId.ToString())
                    };

                    RestResult <ProductRowApiO> apiResult = restClient.Execute <ProductRowApiO>("Product/{key}", RestSharp.Method.DELETE, routeParameters: routeParams, headerParameters: Headers);
                    Assert.True(apiResult.StatusCode == 301, apiResult.Content);
                }

                ProductRowApiO dbValue = sqlClient.Fill <ProductRowApiO>(GetRecordSql);
                Assert.Null(dbValue);
            }
        }
        public void Create()
        {
            using (MSSQLDbClient sqlClient = new MSSQLDbClient(ConnectionString))
            {
                ProductRowApiO existing = sqlClient.Fill <ProductRowApiO>(GetRecordSql);
                if (existing != null)
                {
                    this.Delete();
                }

                using (RESTClient restClient = new RESTClient(BaseUrl))
                {
                    ProductRowApiO newItem = new ProductRowApiO()
                    {
                        ProductName = TestProductName, CategoryId = 2, QuantityPerUnit = "4 in a box", UnitPrice = (decimal)12.37, SupplierId = 1
                    };

                    RestResult <ProductRowApiO> apiResult = restClient.Execute <ProductRowApiO>("Product", RestSharp.Method.PUT, jsonBody: newItem, headerParameters: Headers);
                    Assert.True(apiResult.StatusCode == 201, apiResult.Content);

                    ProductRowApiO sqlResult = sqlClient.Fill <ProductRowApiO>(GetRecordSql);
                    Assert.True(sqlResult.ProductName == apiResult.Result.ProductName &&
                                sqlResult.CategoryId == apiResult.Result.CategoryId &&
                                sqlResult.QuantityPerUnit == apiResult.Result.QuantityPerUnit &&
                                sqlResult.ProductId == apiResult.Result.ProductId);
                }
            }
        }
        public override async Task <Collection <ExchangePairPrice> > GetPairs(CurrencySymbol baseSymbol, PriceType priceType)
        {
            var retVal = new Collection <ExchangePairPrice>();
            var prices = await RESTClient.GetAsync <Collection <PairPrice> >("/api/v1/ticker/price");

            foreach (var price in prices)
            {
                var toSymbolName   = price.symbol.Substring(0, price.symbol.Length - 3);
                var baseSymbolName = price.symbol.Substring(price.symbol.Length - 3, 3);

                var currentBaseSymbol = new CurrencySymbol(baseSymbolName);

                if (baseSymbol != null)
                {
                    if (!currentBaseSymbol.Equals(baseSymbol))
                    {
                        continue;
                    }
                }

                retVal.Add(new ExchangePairPrice(null)
                {
                    BaseSymbol = baseSymbol, ToSymbol = new CurrencySymbol(toSymbolName), Price = price.price
                });
            }

            return(retVal);
        }
        private async void downPlay_Click(object sender, RoutedEventArgs e)
        {
            List <Record> recordList = RESTClient.GetRecordByID(int.Parse(MainPage.userSettings._userID));

            if (playbackList.Items.Count != 0)
            {
                delPlay_Click(this, null);
            }
            foreach (Record record in recordList)
            {
                StorageFolder storageFolder = KnownFolders.VideosLibrary;
                StorageFile   file          = await storageFolder.GetFileAsync(record.videoname);

                var thumbnail = await file.GetScaledImageAsThumbnailAsync(ThumbnailMode.VideosView);

                WriteableBitmap            writeableBitmap    = new WriteableBitmap(100, 64);
                InMemoryRandomAccessStream randomAccessStream = new InMemoryRandomAccessStream();
                await RandomAccessStream.CopyAsync(thumbnail, randomAccessStream);

                randomAccessStream.Seek(0);
                writeableBitmap.SetSource(randomAccessStream);

                MediaModel media = new MediaModel(file)
                {
                    Title            = file.Name,
                    ArtUri           = writeableBitmap,
                    PlaybackPosition = TimeSpan.Parse(record.record),
                    PlaybackHistory  = DateTime.Parse(record.LastOpened)
                };
                pVLis.Items.Add(media);
                playbackList.Items.Add(media.MediaPlaybackItem);
            }
        }
Example #29
0
        public async Task GetOne_ReturnsNull_WhenInvalid()
        {
            var client   = new RESTClient("https://jsonplaceholder.typicode.com");
            var blogPost = await client.GetOne <BlogPost>("posts", int.MaxValue);

            Assert.Null(blogPost);
        }
Example #30
0
        public override async Task <BlockChainAddressInformation> GetAddress(string address)
        {
            var addressModel = await RESTClient.GetAsync <Account>($"/accounts/{address}");

            //TODO: Get a transaction list?
            return(new BlockChainAddressInformation(addressModel.account_id, null, addressModel.balances.FirstOrDefault().balance));
        }
        public void StartSearch(string query)
        {
            Reset();

            SearchQuery = query;
            HasStarted = true;

            restClient = new RESTClient();
            Results = restClient.Get<List<string>>(endpoint, new { tag = SearchQuery });
        }
Example #32
0
        static void Main(string[] args)
        {
            dynamic me = new RESTClient();

            me.Url = "http://api.flickr.com";

            me.OutputPipeLine.Add(1, new Tuple<string, Action<Request>>("addapikey", r => r.Uri = r.Uri + "&api_key=0936270ae439d42bce22ee3be8703112"));

            IAmAFlickr client = Impromptu.ActLike<IAmAFlickr>(me);
            Console.WriteLine ("---------------------- getinfoonpeople");
            Console.WriteLine (client.GetInfoOnPeople<rsp>(new { user_id = "61304303%40N08"}));
            Console.WriteLine ("---------------------- echotest");
            Console.WriteLine (client.EchoTest(new { i_am_a = "banana", and_the_world_should_be_square = true }));
            Console.ReadLine  ();
        }
Example #33
0
        public static IStorageClient GetStorageClient()
        {
            dynamic client = new RESTClient {Url = "http://localhost:8081"};

            client.AddRule.Out = new Func<DynamicRule, byte[]>(rule =>
            {
                using (var ms = new MemoryStream())
                {
                    Serializer.Serialize(ms, rule);
                    return ms.ToArray();
                }
            });

            client.GetRules.In = new Func<WebResponse, IEnumerable<DynamicRule>>(wr => Serializer.Deserialize<List<DynamicRule>>(wr.GetResponseStream()));

            //return null;
            return Impromptu.ActLike<IStorageClient> (client);
        }
 public void ShouldBeAbleToDeserializeProtocolBuffers()
 {
     byte[] buffer;
     using (var ms = new MemoryStream())
     {
         Serializer.Serialize(ms, new AModel { D = 0.1, I = 1, L = 2, S = "s" });
         buffer = ms.ToArray();
     }
     var test = TestWebRequestCreate.CreateTestRequest(buffer);
     test.ContentType = "application/protocol-buffers";
     dynamic me = new RESTClient();
     me.Url = "test://test";
     var a = me.GetTest<AModel>();
     Assert.AreEqual(typeof(AModel), a.GetType());
     Assert.AreEqual(a.D, 0.1);
     Assert.AreEqual(a.I, 1);
     Assert.AreEqual(a.L, 2L);
     Assert.AreEqual(a.S, "s");
 }
        public void EnsureThatTheSpecifiedInputEditorGetsUsed()
        {
            TestWebRequestCreate.CreateTestRequest("dummy");
            dynamic me = new RESTClient();
            me.Url = "test://test";
            me.GetTest.In = new Func<Response, string>(w =>
            {
                string test;
                using (var sr = new StreamReader(w.ResponseStream))
                    test = sr.ReadToEnd();

                Assert.AreEqual(test, "dummy");
                return "";
            });
            me.GetTest();
        }
 public void EnsureThatTheSpecifiedOuputEditorGetsUsed()
 {
     TestWebRequestCreate.CreateTestRequest("dummy");
     dynamic me = new RESTClient();
     me.Url = "test://test";
     me.GetTest.Out = new Func<string, Request>(s =>
     {
         Assert.AreEqual(s, "test");
         return new Request {Body = Encoding.UTF8.GetBytes(s)};
     });
     me.GetTest("test");
 }
        public void MultipleNounTest()
        {
            TestWebRequestCreate.CreateTestRequest("");

            dynamic me = new RESTClient();
            me.Url = "test://base";
            var check = false;
            me.GetMultipleNounTest.In = new Func<Response, string>(w =>
            {
                Assert.AreEqual(new Uri("test://base/multiple/noun/test"), w.ResponseUri);
                check = true;
                return "yes";
            });
            me.GetMultipleNounTest();
            Assert.IsTrue(check);
        }
        public void OneWordFunctionsShouldAlwaysBeGetFunctions()
        {
            var request = TestWebRequestCreate.CreateTestRequest ("");

            var client = new RESTClient ();

            //register the default URI composer because the one below automaticaly takes precedence over the default one.

            client.Container.Register(typeof (IUriComposer), typeof (DefaultUriComposer));

            dynamic me = client;

            me.Url = "test://base";
            me.Noun.In = new Func<Response, string> (w =>
            {
                Assert.AreEqual (new Uri ("test://base/noun/test"), w.ResponseUri);
                return "yes";
            });
            me.Noun ("test");
            Assert.AreEqual ("GET", request.Method);
        }
        public void EnsureArgumentDelegatesTakePrecedenceOverPredefinedDelegates()
        {
            TestWebRequestCreate.CreateTestRequest(5);
            dynamic me = new RESTClient();
            me.Url = "test://test";
            me.GetTest.In = new Func<Response, int>(s =>
            {
                Assert.Fail("Wrong delegate got called!");
                using (var sr = new BinaryReader(s.ResponseStream))
                    return sr.ReadInt32();

            });

            var result = me.GetTest(new Func<Response, int>(s => 4));

            Assert.AreEqual(result, 4);
        }
 public void EnsureCorrenctFillingOfOutputEditorArgumentsWhenTheyArentCorrectlySorted()
 {
     var isused = false;
     TestWebRequestCreate.CreateTestRequest("dummy");
     dynamic me = new RESTClient();
     me.Url = "test://test";
     me.GetTest.Out =
         new Func<int, int, string, long, int, string, string, Request>((i1, i2, s1, l1, i3, s2, s3) =>
         {
             isused = true;
             Assert.AreEqual(i1, 1);
             Assert.AreEqual(i2, 2);
             Assert.AreEqual(s1, "3");
             Assert.AreEqual(l1, 4);
             Assert.AreEqual(i3, 5);
             Assert.AreEqual(s2, "6");
             Assert.AreEqual(s3, "7");
             return new Request();
         });
     me.GetTest(1, 2, 5, "3", "6", "7", (long) 4);
     Assert.IsTrue(isused);
 }
        public void ShouldBeAbleToAddAHeaderInAOutputPipeLine()
        {
            var req = TestWebRequestCreate.CreateTestRequest("dummy");
            dynamic me = new RESTClient();
            me.Url = "test://test";

            me.OutputPipeLine.Add(0.002, Tuple.Create("pipelineitem", new Action<Request>(r => r.Headers.Add("Authorization", "yes"))));

            me.GetTest();
            Assert.AreEqual("yes", req.Headers["Authorization"]);
        }
        public void ShouldBeAbleToChangeTheWayURLsAreBuiltUp()
        {
            TestWebRequestCreate.CreateTestRequest ("dummy");

            var client = new RESTClient ();

            dynamic me = client;

            me.Url = "test://base";
            me.GetTest.In = new Func<Response, Stream> (r =>
            {
                Assert.AreEqual(r.ResponseUri, "test://base/test/param/");
                return r.ResponseStream;
            });
            me.GetTest ("param");

            TestWebRequestCreate.CreateTestRequest ("dummy");

            me.GetTest.In = new Func<Response, Stream> (r =>
            {
                Assert.AreEqual (new Uri ("test://base/test/param1/param2/"), r.ResponseUri);
                return r.ResponseStream;
            });
            me.GetTest ("param1", "param2");
        }
 public void ShouldBeAbleToDeserializeADateTime()
 {
     var test = TestWebRequestCreate.CreateTestRequest(@"""/Date(1307871513107)/""");
     test.ContentType = "application/json";
     dynamic me = new RESTClient();
     me.Url = "test://test";
     var a = me.GetTest<DateTime>();
     Assert.AreEqual(typeof (DateTime), a.GetType());
 }
Example #44
0
 public Response(RESTClient client)
 {
     _client = client;
 }
        public void UrlParameterArguments()
        {
            TestWebRequestCreate.CreateTestRequest("dummy");

            dynamic me = new RESTClient();
            me.Container.Register(typeof(IUriComposer), typeof(DefaultUriComposer));
            me.Url = "test://base";
            me.GetTest.In = new Func<Response, Stream>(r =>
            {
                Assert.AreEqual(new Uri("test://base/test/param"), r.ResponseUri);
                return r.ResponseStream;
            });
            me.GetTest("param");

            TestWebRequestCreate.CreateTestRequest("dummy");

            me.GetTest.In = new Func<Response, Stream>(r =>
            {
                Assert.AreEqual(new Uri("test://base/test/param1/param2"), r.ResponseUri);
                return r.ResponseStream;
            });
            me.GetTest("param1", "param2");
        }
        public void EnsureAFunctionCallWithEverythingAlsoWorks()
        {
            TestWebRequestCreate.CreateTestRequest("dummy");

            dynamic me = new RESTClient();
            me.Container.Register(typeof (IUriComposer), typeof (DefaultUriComposer));

            me.Url = "test://base";

            var result = me.GetTest<string>(
                /*QueryString*/
                new {page = "1", items = "50"},
                /*OutputEditorArguments*/
                1, 2, 3, 4, "5", "6",
                /*URLParam*/
                "param",
                /*OutputEditor*/
                new Func<int, string, int, string, int, int, Request>(
                    (i1, s1, i2, s2, i3, i4) =>
                    {
                        Assert.AreEqual(i1, 1);
                        Assert.AreEqual(s1, "5");
                        Assert.AreEqual(i2, 2);
                        Assert.AreEqual(s2, "6");
                        Assert.AreEqual(i3, 3);
                        Assert.AreEqual(i4, 4);
                        return new Request {Body = new byte[16]};
                    }),
                /*InputEditor*/
                new Func<Response, string>(w =>
                {
                    Assert.AreEqual(w.ResponseUri, "test://base/test/param?page=1&items=50");
                    using (var sr = new StreamReader(w.ResponseStream))
                        return sr.ReadToEnd();
                }));
            Assert.AreEqual(result, "dummy");
        }
 public void EnsureExceptionWhenThereAreArgumentsMissingForOutputEditor()
 {
     dynamic me = new RESTClient();
     //me.GetTest.In = new Func<Stream, int> (s => 1);
     me.GetTest.Out =
         new Func<int, int, string, long, int, string, string, Request>(
             (i1, i2, s1, l1, i3, s2, s3) => new Request {Body = new byte[12]});
     me.GetTest(1, 2, "3", (long) 4, /* missing5,*/ "6", "7");
 }
 public void EnsureExceptionWhenGenericTypeDoesNotEqualInputEditorOutputType()
 {
     dynamic me = new RESTClient();
     me.GetTest.In = new Func<Response, int>(s => 1);
     me.GetTest<string>("test");
 }
 public void PutVerbTest()
 {
     var request = TestWebRequestCreate.CreateTestRequest("");
     dynamic me = new RESTClient();
     me.Url = "test://base";
     me.PutTest.Out = new Func<int, Request>(i => new Request {Body = BitConverter.GetBytes(i)});
     me.PutTest(1);
     Assert.AreEqual(BitConverter.ToInt32(((MemoryStream) request.GetRequestStream()).ToArray(), 0), 1);
 }
 public void EnsureCorrenctFillingOfOutputEditorArguments()
 {
     TestWebRequestCreate.CreateTestRequest("dummy");
     dynamic me = new RESTClient();
     me.Url = "test://test";
     me.GetTest.Out =
         new Func<int, int, string, long, int, string, string, Request>((i1, i2, s1, l1, i3, s2, s3) =>
         {
             Assert.AreEqual(i1, 1);
             Assert.AreEqual(i2, 2);
             Assert.AreEqual(s1, "3");
             Assert.AreEqual(l1, 4);
             Assert.AreEqual(i3, 5);
             Assert.AreEqual(s2, "6");
             Assert.AreEqual(s3, "7");
             return new Request();
         });
     me.GetTest(1, 2, "3", (long) 4, 5, "6", "7");
 }
        public void OutputEditorInArgumentWithLotsOfArguments()
        {
            TestWebRequestCreate.CreateTestRequest("dummy");

            dynamic me = new RESTClient();
            me.Url = "test://base";

            var result = me.GetTest(1, 2, 3, 4, 5, (long) 6, "7", "8", true,
                                    new Func<bool, string, long, string, int, int, int, int, int, Request>(
                                        (a, b, c, d, e, f, g, h, i) =>
                                        {
                                            Assert.IsTrue(a);
                                            Assert.AreEqual(b, "7");
                                            Assert.AreEqual(c, 6);
                                            Assert.AreEqual(d, "8");
                                            Assert.AreEqual(e, 1);
                                            Assert.AreEqual(f, 2);
                                            Assert.AreEqual(g, 3);
                                            Assert.AreEqual(h, 4);
                                            Assert.AreEqual(i, 5);
                                            return new Request {Body = new byte[16]};
                                        }),
                                    new Func<WebResponse, WebResponse>(r => r));

            Assert.AreEqual(new Uri("test://base/test"), result.ResponseUri);
        }
Example #52
0
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="pattern">zoek pattern</param>
        /// <param name="limitRate">lief zijn (of niet)</param>
        public RunningTotal(string pattern, bool limitRate)
        {
            LimitRate = limitRate;
            Realtors = new ConcurrentDictionary<int, Realtor> ();
            _pattern = pattern;

            //de rest client http://nuget.org/packages/DRC en https://github.com/albertjan/DynamicRestClient
            dynamic client = new RESTClient(uriComposer: new AlternativeUriComposer());

            //geen basis url op.
            client.Url = "http://partnerapi.funda.nl/feeds/Aanbod.svc";

            //Iets wat ik een input editor noem een delegate die een webresponse vertaald naar het geweste object.
            //Als ik de duck-casting weg zou laten zou dit automatisch gaan maar dan zou de type-safety verder op.
            //Als de resquest GetJson<FundaResult>(ApiKey, params) zou zijn zou de DRC aan de hand van het
            //generic-type-argument zien waarnaar hij het resultaat moet parsen. Maar ImpromptuInterface ondersteund
            //niet het casten naar Interface's die Generic functies bevatten.
            client.GetJson.In = new Func<WebResponse, FundaResult>(r =>
            {
                using (var sr = new StreamReader(r.GetResponseStream()))
                {
                    return DRC.SimpleJson.DeserializeObject<FundaResult>(sr.ReadToEnd());
                }
            });

            //ImpromptuInterface gebruiken om van de dynamic client een semi typesafe object te maken.
            FundaClient = Impromptu.ActLike<IFundaClient>(client);
        }
        public void ShouldExecutePipeLineEntries()
        {
            TestWebRequestCreate.CreateTestRequest("dummy");
            dynamic me = new RESTClient();
            me.Url = "test://test";

            var pipelinetest = "apeshit";
            var pipelinetest2 = "apeshit";

            me.InputPipeLine.Add(2.5,
                                 Tuple.Create("pipelineitem", new Action<Response>(resp => { pipelinetest = "yep"; })));
            me.OutputPipeLine.Add(0.002,
                                  Tuple.Create("pipelineitem",
                                               new Action<Request>(resp => { pipelinetest2 = "yep"; })));

            me.GetTest.In = new Func<Response, string>(w =>
            {
                string test;
                using (var sr = new StreamReader(w.ResponseStream))
                    test = sr.ReadToEnd();

                Assert.AreEqual(test, "dummy");
                return "";
            });
            me.GetTest();

            Assert.AreEqual("yep", pipelinetest);
            Assert.AreEqual("yep", pipelinetest2);
        }
        public void ShouldReturnTheContentsAsAStringWhenConvertedToOneEvenIfTheContentTypeIsSerialiazble()
        {
            var test =
                TestWebRequestCreate.CreateTestRequest(
                    SimpleJson.SerializeObject(new AModel { D = 0.1, I = 1, L = 2, S = "s" }));
            test.ContentType = "application/json";
            dynamic me = new RESTClient();
            me.Url = "test://test";
            string a = me.GetTest();

            Assert.AreEqual(typeof(string), a.GetType());
            Assert.AreEqual("{\"I\":1,\"S\":\"s\",\"L\":2,\"D\":0.1}", a);
        }
        public void ShouldUseSpecifiedUrl()
        {
            TestWebRequestCreate.CreateTestRequest("dummy");
            dynamic me = new RESTClient();
            me.Url = "test://test";

            me.GetTest.Url = "bananas/overthere";

            me.OutputPipeLine.Add(0.1,
                                  Tuple.Create("hi",
                                               new Action<Request>(
                                                   r =>
                                                   Assert.AreEqual("test://test/bananas/overthere",
                                                                   r.Uri))));

            me.GetTest();
        }
 public void ShouldTryToDeserializeJsonToGenericTypeArgument()
 {
     var test =
         TestWebRequestCreate.CreateTestRequest(
             SimpleJson.SerializeObject(new AModel {D = 0.1, I = 1, L = 2, S = "s"}));
     test.ContentType = "application/json";
     dynamic me = new RESTClient();
     me.Url = "test://test";
     var a = me.GetTest<AModel>();
     Assert.AreEqual(typeof (AModel), a.GetType());
 }
 public void ShouldTryToDeserializeXMLToGenericTypeArgument()
 {
     string xml;
     using (var ms = new MemoryStream())
     using (var sw = new StreamWriter(ms))
     {
         new XmlSerializer(typeof (AModel)).Serialize(sw, new AModel {D = 0.1, I = 1, L = 2, S = "s"});
         sw.Flush();
         ms.Position = 0;
         using (var sr = new StreamReader(ms))
         {
             xml = sr.ReadToEnd();
         }
     }
     var test = TestWebRequestCreate.CreateTestRequest(xml);
     test.ContentType = "application/xml";
     dynamic me = new RESTClient();
     me.Url = "test://test";
     var a = me.GetTest<AModel>();
     Assert.AreEqual(typeof (AModel), a.GetType());
 }
 public void ShouldBeAbleToDeserializeAGuid()
 {
     var test = TestWebRequestCreate.CreateTestRequest(@"""378eb2ddc6d4461b9b4cf77ef0098daf""");
     test.ContentType = "application/json";
     dynamic me = new RESTClient();
     me.Url = "test://test";
     var a = me.GetTest<Guid>();
     Assert.AreEqual(typeof (Guid), a.GetType());
 }
        public ActionResult ProcessRequest(ApiTestRequest request)
        {
            // Base uri
            string baseUri = ConfigurationManager.AppSettings["LitmosAPIBaseUri"].ToString();

            RESTResponse rs = new RESTResponse();
            RESTClient client = new RESTClient(baseUri, request.ApiKey, request.Source);
            RequestFactory factory = new RequestFactory(baseUri, request.ApiKey, request.Source);

            switch (request.RequestType)
            {
                case "USERS": // Get a List of Users
                    // Get
                    var listUsers = factory.ListUsers(Request.Form["Filter"]);

                    // Format Response
                    request.ResponseBody = GetUserList(listUsers);
                    break;

                case "USER": // Get a User
                    // Get
                    var singleUser = factory.GetUser(Request.Form["UserId"]);

                    // Format Response
                    request.ResponseBody = GetUser(singleUser);
                    break;

                case "CREATE_USER": // Create a User

                    UserProfile createUser = new UserProfile(Request.Form["UserName"], Request.Form["FirstName"], Request.Form["LastName"]);

                    // Create
                    var newUser = factory.CreateUser(createUser);

                    // Format Response
                    request.ResponseBody = GetUser(newUser);
                    break;

                case "UPDATE_USER": // Update a User

                    // Get User
                    var updateUser = factory.GetUser(Request.Form["UserId"]);

                    // Update User Properties
                    if (updateUser != null)
                    {
                        updateUser.Id = Request.Form["UserId"];
                        updateUser.FirstName = Request.Form["FirstName"];
                        updateUser.LastName = Request.Form["LastName"];

                        // Update 
                        updateUser = factory.UpdateUser(Request.Form["UserId"], updateUser);
                    }
                    break;

                case "TEAMS": // Get a List of Teams
                    request.ResponseBody = GetTeamList(factory.ListTeams(Request.Form["Filter"]));
                    break;

                case "SUBTEAMS": // Get a List of sub Teams
                    // Get
                    var subTeams = factory.ListTeams(Request.Form["TeamId"], Request.Form["Filter"]);

                    // Format Response
                    request.ResponseBody = GetTeamList(subTeams);
                    break;

                case "ADD_TEAMUSERS": // Get a List of Teams
                    
                    var users = new UserList();

                    users.Add(new UserProfilePartial(){
                        Id = Request.Form["UserId"]
                    });

                    var userTeamSuccess = factory.AddUsersToTeam(Request.Form["TeamId"], users);

                    // Format Response
                    request.ResponseBody = userTeamSuccess ? "Users added to team!" : "Users to team FAILED";
                    break;

                case "TEAMUSERS": // Get a List of Users
                    // Get
                    var listTeamUsers = factory.ListTeamUsers(Request.Form["TeamId"]);

                    // Format Response
                    request.ResponseBody = GetUserList(listTeamUsers);
                    break;

                case "PROMOTE_LEADER":
                    var promoteLeader = factory.PromoteTeamLeader(Request.Form["TeamId"], Request.Form["UserId"]);

                    // Format Response
                    request.ResponseBody = promoteLeader ? "Users promoted to team leader!" : "Users to team FAILED";
                    break;

                case "DEMOTE_LEADER":
                    var demoteTeamLeader = factory.DemoteTeamLeader(Request.Form["TeamId"], Request.Form["UserId"]);

                    // Format Response
                    request.ResponseBody = demoteTeamLeader ? "Users demoted from team leader!" : "Users to team FAILED";
                    break;

                case "COURSES": // Get a List of Courses
                    // Get
                    var listCourses = factory.ListCourses();

                    // Format Response
                    request.ResponseBody = GetCourseList(listCourses);
                    break;

                case "USER_COURSES": // Get a List of Courses
                    // Get
                    var listUserCourses = factory.ListUserCourses(Request.Form["UserId"]);

                    // Format Response
                    request.ResponseBody = GetUserCourseList(listUserCourses);
                    break;
            }


            if (rs != null)
            {
                request.ResponseStatusCode = rs.StatusCode;
                request.ResponseDescription = rs.StatusDescription;
            }

            return View("Index", request);
        }