示例#1
0
文件: Program.cs 项目: dfgs/RESTLib
        static async Task Main(string[] args)
        {
            RESTClient client;
            string     result;
            Book       book;

            RESTServer    server;
            IRouteManager routeManager;

            routeManager = new RouteManager(new RouteParser(), new ResponseSerializer());
            routeManager.AddRouteHandler(new BooksRouteHandlers());
            server = new RESTServer(new ConsoleLogger(new DefaultLogFormatter()), routeManager, "http://localhost:8734/");

            server.Start();
            Thread.Sleep(1000);

            client = new RESTClient(new HttpConnector(), new ResponseDeserializer());

            /*Console.WriteLine("Trying to query URL");
             * result = await client.GetAsync("http://localhost:8734/root/books/500");
             * Console.WriteLine("Result:");
             * Console.WriteLine(result);*/

            Console.WriteLine("Trying to query URL");
            book = await client.GetAsync <Book>("http://localhost:8734/root/books/500");

            Console.WriteLine("Result:");
            Console.WriteLine(book);

            Console.WriteLine("Trying to query URL");
            book = await client.GetAsync <Book>("http://localhost:8734/root/books?year=2020&author=stephenking");

            Console.WriteLine("Result:");
            Console.WriteLine(book);

            Console.WriteLine("Trying to query URL");
            try
            {
                book = await client.GetAsync <Book>("http://localhost:8734/root/book/500");
            }
            catch (Exception ex)
            {
                Console.WriteLine("Result:");
                Console.WriteLine(ex);
            }


            Console.ReadLine();

            server.Stop();
            Console.ReadLine();
        }
示例#2
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();
            }
        }
示例#3
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);
        }
        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);
        }
示例#5
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));
        }
示例#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));
        }
示例#7
0
        /// <summary>
        /// Gets the value of the specified attribute and entity id
        /// </summary>
        /// <returns>The response object</returns>
        public async Task <ContextAttributesResponse> GetAttributeValueForEntityAsync(string entityId, string attributeName)
        {
            RESTClient <ContextAttributesResponse> client = new RESTClient <ContextAttributesResponse>(OrionConfig.AuthHeaderKey, _config.Token);
            string uri = string.Format(OrionConfig.ConvenienceUrlFormatTwoParams, _config.BaseUrl, _config.Version1Path, OrionConfig.ContextEntitiesPath, entityId, OrionConfig.AttributesPath, attributeName);

            return(await client.GetAsync(uri));
        }
示例#8
0
        /// <summary>
        /// Retrieves the entity with the specified id
        /// </summary>
        /// <returns>The response object</returns>
        public async Task <ContextResponse> GetEntityAsync(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.GetAsync(uri));
        }
示例#9
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));
        }
示例#10
0
        public async Task <List <Question> > GetQuestions()
        {
            try
            {
                var restClient = new RESTClient(new SerializationAdapter(), new Uri(ApplicationConstants.Endpoints.TriviaBaseUrl, "api.php?amount=10"));
                var response   = await restClient.GetAsync <GetQuestionsResponse>();

                if (response == null)
                {
                    throw new Exception(restClient.ErrorType.FullName);
                }
                if (response.Status == ResponseCode.Success)
                {
                    return(response.Questions);
                }
                else
                {
                    throw new Exception(response.Status.ToString());
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
示例#11
0
        public override async Task <BlockChainAddressInformation> GetAddress(string address)
        {
            var addressModel = await RESTClient.GetAsync <Address>($"/v2/accounts/{address}/balances");

            var balance = addressModel.balances.FirstOrDefault();

            return(balance == null ? null : new BlockChainAddressInformation(address, null, balance.value));
        }
        public override async Task <BlockChainAddressInformation> GetAddress(string address)
        {
            var addressModel = await RESTClient.GetAsync <Address>($"{AddressQueryStringBase}{address}");

            var retVal = new BlockChainAddressInformation(address, addressModel.balance, addressModel.transactions.Count);

            return(retVal);
        }
示例#13
0
        public async Task ShouldThrowExceptionIfGETStatusCodeIsNotOK()
        {
            RESTClient client;

            client = new RESTClient(new MockedHttpConnector(System.Net.HttpStatusCode.NotFound), new ResponseDeserializer());

            await Assert.ThrowsExceptionAsync <RESTException>(() => client.GetAsync <string>("root/test"));
        }
        public override async Task <BlockChainAddressInformation> GetAddress(string address)
        {
            var addressModel = await RESTClient.GetAsync <Address>($"/ext/getaddress/{address}");

            var retVal = new BlockChainAddressInformation(address, addressModel.balance, addressModel.received == 0);

            return(retVal);
        }
示例#15
0
        public override async Task <BlockChainAddressInformation> GetAddress(string address)
        {
            var addressModel = await RESTClient.GetAsync <Address>($"/api/v1/balances/{address}");

            var balance = addressModel.balances.FirstOrDefault(b => b.name == CurrencySymbol.NEOSymbolName);

            return(balance != null ? new BlockChainAddressInformation(address, null, balance.total) : null);
        }
        public override async Task <BlockChainAddressInformation> GetAddress(string address)
        {
            var account = await RESTClient.GetAsync <Account>($"api/account?address={address}");

            var transactions = await RESTClient.GetAsync <ts.Transaction>($"api/transaction?sort=-timestamp&count=true&limit=1&start=0&address={address}");

            var balance = account.balance;

            return(new BlockChainAddressInformation(account.address, balance * (decimal).000001, transactions.data.Count > 0));
        }
示例#17
0
        /// <summary>
        /// Retrieves all entities
        /// </summary>
        /// <returns>The response object</returns>
        public async Task <ContextResponses> GetAllEntitiesAsync()
        {
            RESTClient <ContextResponses> client = new RESTClient <ContextResponses>(OrionConfig.AuthHeaderKey, _config.Token);
            string           uri = string.Format(OrionConfig.UrlFormat, _config.BaseUrl, _config.Version1Path, OrionConfig.ContextEntitiesPath);
            ContextResponses contextResponses = await client.GetAsync(uri);

            if (contextResponses.Responses == null)
            {
                contextResponses.Responses = new List <ContextResponse>();
            }

            return(contextResponses);
        }
示例#18
0
        public async Task GetMovie(string code)
        {
            Movie result = null;

            try
            {
                result = await client.GetAsync(code);
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
            }
        }
示例#19
0
        public override async Task <BlockChainAddressInformation> GetAddress(string address)
        {
            try
            {
                var addressModel = await RESTClient.GetAsync <Address>($"/v2/mainnet/accounts/{address}");

                return(new BlockChainAddressInformation(address, addressModel.balance, addressModel.totalRecv == 0));
            }
            catch (Exception ex)
            {
                Logger.Log("Error getting ZCash address", ex, LogSection);
                throw;
            }
        }
        public override async Task <BlockChainAddressInformation> GetAddress(string address)
        {
            var json = await RESTClient.GetAsync <string>($"/bitcoin-cash/dashboards/address/{address}");

            var baseObject   = (JObject)JsonConvert.DeserializeObject(json);
            var dataObject   = baseObject["data"];
            var addressToken = dataObject[address];

            addressToken = addressToken["address"];
            var balanceInSatoshis = (long)addressToken["balance"];

            var transactionCountToken = addressToken["transaction_count"];
            var transactionCount      = transactionCountToken.Value <int>();

            return(new BlockChainAddressInformation(address, balanceInSatoshis / CurrencySymbol.Satoshi, transactionCount));
        }
        public override async Task <BlockChainAddressInformation> GetAddress(string address)
        {
            //https://www.blockcypher.com/dev/bitcoin/#rate-limits-and-tokens
            await Task.Delay(MillisecondsDelay);

            //Do a ToLower on ethereum coins but not other coins
            var isEthereum = CurrencySymbol.IsEthereum(Currency);

            address = isEthereum ? address.ToLower() : address;

            var apiKeyPart   = !string.IsNullOrEmpty(APIKey) ? $"?token={APIKey}" : string.Empty;
            var balanceModel = await RESTClient.GetAsync <Address>($"v1/{Currency.Name.ToLower()}/main/addrs/{address}/balance{apiKeyPart}");

            //This website returns satoshis/wei so need to divide
            var balance = isEthereum ? balanceModel.balance / CurrencySymbol.Wei : balanceModel.balance / CurrencySymbol.Satoshi;

            return(new BlockChainAddressInformation(address, balance, balanceModel.final_n_tx));
        }
示例#22
0
        public override async Task <Collection <ExchangePairPrice> > GetPairs(CurrencySymbol baseSymbol, PriceType priceType)
        {
            var retVal  = new Collection <ExchangePairPrice>();
            var symbols = await RESTClient.GetAsync <List <string> >("/v1/symbols");

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

                var currentBaseSymbol = new CurrencySymbol(baseSymbolName);

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

                Tick tick = null;
                while (tick == null)
                {
                    try
                    {
                        tick = await RESTClient.GetAsync <Tick>($"/v1/pubticker/{symbol}");
                    }
                    catch
                    {
                        //Wait for the rate to come back
                        Thread.Sleep(61000);
                    }
                }

                retVal.Add(new ExchangePairPrice(tick.volume)
                {
                    BaseSymbol = currentBaseSymbol, ToSymbol = new CurrencySymbol(toSymbolName), Price = priceType == PriceType.Bid ? tick.bid : tick.ask
                });
            }

            return(retVal);
        }
        public override async Task <BlockChainAddressInformation> GetAddress(string address)
        {
            bool unused;

            var balance = await RESTClient.GetAsync <decimal>($"/chain/Dogecoin/q/addressbalance/{address}");

            if (balance == 0)
            {
                //There is no balance so check to see if the address was ever used
                var received = await RESTClient.GetAsync <Received>($"/api/v1/address/received/{address}");

                unused = received.received == 0;
            }
            else
            {
                unused = false;
            }

            return(new BlockChainAddressInformation(address, balance, unused));
        }
        private async Task <Account> GetAccount()
        {
            //Whacky stuff...
            //No idea why any of this is necessary, but code was pieces together from Binance.NET
            var startTime        = DateTime.Now;
            var binanceTimeModel = await RESTClient.GetAsync <BinanceTime>("/api/v1/time");

            var binanceTime = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddMilliseconds(binanceTimeModel.serverTime);
            var timeTaken   = DateTime.Now - startTime;
            var timeOffset  = ((binanceTime - DateTime.Now).TotalMilliseconds) - timeTaken.TotalMilliseconds / 2;
            var timestamp   = APIHelpers.GetUnixTimestamp(DateTime.UtcNow.AddMilliseconds(timeOffset)).ToString();
            var queryString = $"api/v3/account?recvWindow=10000000000&timestamp={timestamp}";
            var uri         = new Uri($"{RESTClient.BaseUri}{queryString}");
            var hmacAsBytes = APIHelpers.GetHashAsBytes(uri.Query.Replace("?", ""), ApiSecret, APIHelpers.HashAlgorithmType.HMACEightBit, Encoding.UTF8);

            queryString += $"&signature={hmacAsBytes.ToHexString()}";
            RESTClient.Headers.Clear();
            RESTClient.Headers.Add("X-MBX-APIKEY", ApiKey);
            return(await RESTClient.GetAsync <Account>(queryString));
        }
        public override async Task <Collection <ExchangePairPrice> > GetPairs(CurrencySymbol baseSymbol, PriceType priceType)
        {
            if (baseSymbol == null)
            {
                throw new ArgumentNullException(nameof(baseSymbol));
            }

            var retVal = new Collection <ExchangePairPrice>();
            var prices = await RESTClient.GetAsync <Prices>($"/api/GetMarkets/{baseSymbol.Name}");

            foreach (var pair in prices.Data)
            {
                var toSymbolName   = pair.Label.Substring(0, 3);
                var baseSymbolName = pair.Label.Substring(4, pair.Label.Length - 4);

                var currentBaseSymbol = new CurrencySymbol(baseSymbolName);
                if (!currentBaseSymbol.Equals(baseSymbol))
                {
                    continue;
                }

                if (pair.LastPrice == 0)
                {
                    continue;
                }

                //Duplicate coin name
                if (toSymbolName == "BTG" || toSymbolName == "BAT" || toSymbolName == "PLC" || toSymbolName == "CMT" || toSymbolName == "ACC")
                {
                    continue;
                }

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

            return(retVal);
        }
示例#26
0
        public async Task <ChargeState> GetChargeState(string vehicleId)
        {
            if (!IsLoggedIn)
            {
                await Login();
            }

            var path = $"api/1/vehicles/{vehicleId}/data_request/charge_state";

            var outcome = await PollyUtility.ExecuteWebRequest(async() =>
            {
                return(await _api.GetAsync <ChargeState>(path, new Dictionary <string, string> {
                    { "Authorization", AuthorizationHeader }
                }));
            });

            if (outcome.Outcome == OutcomeType.Failure)
            {
                return(ChargeState.Empty);
            }

            return(outcome.Result);
        }
示例#27
0
        /// <summary>
        /// Private IR Call: GetAccounts
        /// </summary>
        /// <returns></returns>
        private async Task <List <Balance> > Balances()
        {
            //TODO: Why is this different to the other APIS? Consolidate....
            var nonce            = APIHelpers.GetNonce();
            var bitfinexPostBase = new BitfinexPostBase {
                Request = BalanceRequestUrl, Nonce = nonce
            };
            var jsonObj = JsonConvert.SerializeObject(bitfinexPostBase);
            var payload = Convert.ToBase64String(Encoding.UTF8.GetBytes(jsonObj));

            RESTClient.Headers.Clear();
            RESTClient.Headers.Add("X-BFX-APIKEY", ApiKey);
            RESTClient.Headers.Add("X-BFX-PAYLOAD", payload);

            //Notice the ToLower here. This is specific to Bitfinex
            var signature = APIHelpers.GetHash(payload, ApiSecret, APIHelpers.HashAlgorithmType.HMACThreeEightFour, Encoding.UTF8).ToLower();

            RESTClient.Headers.Add("X-BFX-SIGNATURE", signature);

            var retVal = await RESTClient.GetAsync <List <Balance> >(BalanceRequestUrl);

            return(retVal);
        }
        /// <summary>
        /// Private IR Call: GetAccounts
        /// </summary>
        /// <returns></returns>
        private async Task <List <Balance> > Balances()
        {
            //get the epoch timestamp to be used as the nonce
            //BTC Markets moans about timestamps for some damned reason so we need to get the time from ConvertUnixTime
            var timestamp = APIHelpers.GetCurrentUnixTimestamp().ToString();

            // create the string that needs to be signed
            var stringToSign = BuildStringToSign(ACCOUNT_BALANCE_PATH, null, timestamp);

            // build signature to be included in the http header
            //TODO: API Secret?
            var signature = ComputeHash(ApiSecret, stringToSign);

            lock (RESTClient.Headers)
            {
                RESTClient.Headers.Clear();
                RESTClient.Headers.Add("Accept", HeaderConstants.CONTENT);
                RESTClient.Headers.Add("Accept-Charset", HeaderConstants.ENCODING);
                RESTClient.Headers.Add(HeaderConstants.APIKEY_HEADER, ApiKey);
                RESTClient.Headers.Add(HeaderConstants.SIGNATURE_HEADER, signature);
                RESTClient.Headers.Add(HeaderConstants.TIMESTAMP_HEADER, timestamp);
            }

            List <Balance> result;

            try
            {
                result = await RESTClient.GetAsync <List <Balance> >(ACCOUNT_BALANCE_PATH);
            }
            catch (DeserializationException dex)
            {
                var errorResult = JsonConvert.DeserializeObject <ErrorResult>(dex.Markup);
                throw new BTCMarketsException(errorResult);
            }

            return(result);
        }
        /// <summary>
        /// TODO: This shouldn't directly override the method. There should be a func instead.
        /// </summary>
        public override async Task <TransactionsAtAddress> GetTransactionsAtAddress(string address)
        {
            var lastUpdate     = DateTime.Now;
            var insightAddress = await GetInsightAddress(address);

            var returnValue = new TransactionsAtAddress(address, insightAddress.transactions.Select(t => new Transaction(t)))
            {
                LastUpdate = lastUpdate
            };

            foreach (var transaction in returnValue.Transactions)
            {
                var insightTransaction = await RESTClient.GetAsync <insight.Transaction>($"{TransactionQueryStringBase}{transaction.TransactionId}");

                transaction.TransactionId = insightTransaction.txid;
                transaction.Fees          = insightTransaction.fees;
                foreach (var vin in insightTransaction.vin)
                {
                    transaction.Inputs.Add(new TransactionPiece {
                        Value = vin.value, Address = vin.addr
                    });
                }

                foreach (var vout in insightTransaction.vout)
                {
                    transaction.Outputs.Add(new TransactionPiece
                    {
                        Value = vout.value,
                        //TODO: Not sure if this logic is correct...
                        Address = vout.scriptPubKey.addresses.FirstOrDefault()
                    });
                }
            }

            return(returnValue);
        }
        private async Task <Address> GetAddressModel(string address)
        {
            var apiKeyPart = !string.IsNullOrEmpty(APIKey) ? $"?apiKey={APIKey}" : string.Empty;

            return(await RESTClient.GetAsync <Address>($"/getAddressInfo/{address}{apiKeyPart}"));
        }