Example #1
0
        public void CanGetPetsWithoutError()
        {
            var pets = ApiReader.GetAvailablePets();

            Assert.IsTrue(pets != null);
            Assert.IsTrue(pets.Length > 0);
        }
Example #2
0
        static void Main(string[] args)
        {
            //Get Available Pets
            var pets = ApiReader.GetAvailablePets();

            //Check if there are no pets available
            if (pets == null || pets.Length <= 0)
            {
                Console.WriteLine("No available pets");
                return;
            }

            //Sort pets by category and reversed pet name
            var sorted = pets.SortPetsByCategory().SortPetsByNameInReverse();

            //output available pets
            Console.WriteLine("Avaliable pets");
            foreach (var category in sorted)
            {
                Console.WriteLine("Category: {0}", category.Name);
                if (category.Pets == null || category.Pets.Count <= 0)
                {
                    continue;
                }
                foreach (var pet in category.Pets)
                {
                    Console.WriteLine(pet.Name == null ? string.Empty : @pet.Name);
                }
            }
        }
Example #3
0
        /// <summary>
        /// Checks TimerElapsed() functions correctly. Currently non-functional, use the python price updater instead.
        /// </summary>
        //[TestMethod()]
        public void PriceUpdater_TimerElapsedTest()
        {
            int timeOfInsert = ApiReader.GetUnixTime();

            Program.APR = new ApiReader();                                                               // Initialises ApiReader
            Program.DBC = new DatabaseConnector();                                                       // Initialises DatabaseConnector

            Program.currency = new CurrencyPair(2, 1);                                                   // Creates new currency pair of ETH/BTC

            Program.TimerElapsed(null, null);                                                            // Runs TimerElapsed

            List <DatabaseRow> values = Program.DBC.SelectAllFromDatabase();                             // Selects every row from the database

            bool hasBeenFound = false;                                                                   // False until found

            foreach (DatabaseRow row in values)                                                          // Iterates through every row
            {
                if (Convert.ToInt32(row.data[0]) == Program.LastInsert)                                  // If the row is the values previously inserted
                {
                    hasBeenFound = true;                                                                 // Test is passed
                    string        sql     = "DELETE FROM prices WHERE date=" + Program.LastInsert + ";"; // Create sql to delete the row
                    SQLiteCommand command = new SQLiteCommand(sql, Program.DBC.connection);              // Create the command
                    command.ExecuteNonQuery();                                                           // Execute the command
                }
            }

            Assert.AreEqual(timeOfInsert, Program.LastInsert);
            Assert.IsTrue(hasBeenFound);
        }
Example #4
0
        static async Task Main(string[] args)
        {
            var config = new ConfigurationBuilder()
                         .AddJsonFile("appsettings.json", true, true)
                         .Build();

            var serviceProvider = new ServiceCollection()
                                  .AddSingleton <HttpClient>()
                                  .BuildServiceProvider();

            var apiUrl = config["apiUrl"];

            var httpClient = serviceProvider.GetService <HttpClient>();
            var reader     = new ApiReader(httpClient);
            // Read with specific shape
            //var metaWeather = await reader.ReadFromUrlAsync<MetaWeather>(apiUrl);
            //WeatherHelper.PrintInfo(metaWeather);

            // Read dynamically
            var jsonString = await reader.ReadAsString(apiUrl);

            DynamicJsonReaderHelper.ReadFromString(jsonString);

            Console.ReadKey();
        }
Example #5
0
        /// <summary>
        /// Run every 10 seconds, gets data from the API and puts it into the database.
        /// </summary>
        public static void TimerElapsed(object sender, ElapsedEventArgs e)
        {
            LastInsert = ApiReader.GetUnixTime();

            TickerResult       ticker  = APR.GetTickerResult(currency);       // Gets the ticker for the specified currency
            TradeHistoryResult history = APR.GetTradeHistoryResult(currency); // Gets the trade history for the specified currency

            Console.Write("Got price " + ticker.lastPrice + " at time " + LastInsert + "... ");

            double volAsk = 0;
            double volBid = 0;

            foreach (HistoricalTrade trade in history.trades)
            {
                if (trade.IsBid)
                {
                    volBid += trade.Amount;
                }
                else
                {
                    volAsk += trade.Amount;
                }
            }

            //DatabaseRow row = new DatabaseRow(
            //    LastInsert,
            //    ticker.lastPrice,
            //    volBid,
            //    volAsk);
            //DBC.InsertIntoDatabase(row);

            //Console.WriteLine("Inserted.");
            Console.WriteLine("Skipping insertion, no longer implemented in C#. Speak to me if you'd like me to reimplement this, it shouldn't take too long.");
        }
        public void SendRequest_ShouldRequestANewTokenIfExpired()
        {
            Task.Run(async() =>
            {
                string expired   = readMockDataFromFile($"/../../../MockData/expiredTokenMock.json");
                string valid     = readMockDataFromFile($"/../../../MockData/tokenMock.json");
                var expectedDict = JsonConvert.DeserializeObject <Dictionary <string, string> >(valid);

                var client   = new Mock <IWebClient>();
                var response = new Mock <IApiResponse>();
                response.Setup(i => i.IsSuccessful()).Returns(true);
                response.Setup(i => i.ReadContentAsync()).ReturnsAsync(expired);

                client.Setup(i => i.RequestAccessTokenAsync()).ReturnsAsync(response.Object);
                client.Setup(i => i.MakeApiRequestAsync(It.IsAny <string>())).ReturnsAsync(response.Object);

                var reader = new ApiReader(defaultConfig, client.Object);
                try
                {
                    await reader.GetAsync <Dictionary <string, string> >("anything");
                    response.Setup(i => i.ReadContentAsync()).ReturnsAsync(valid);
                    var answer = await reader.GetAsync <Dictionary <string, string> >("anything");
                    answer.Should().BeEquivalentTo(expectedDict);
                }
                catch
                {
                    Assert.Fail();
                }
            }).GetAwaiter().GetResult();
        }
        public void SendRequestToken_ShouldGetTokenFromJsonCorrectly()
        {
            Task.Run(async() =>
            {
                string json = readMockDataFromFile($"/../../../MockData/tokenMock.json");

                var client   = new Mock <IWebClient>();
                var response = new Mock <IApiResponse>();
                response.Setup(i => i.IsSuccessful()).Returns(true);
                response.Setup(i => i.ReadContentAsync()).ReturnsAsync(json);

                client.Setup(i => i.RequestAccessTokenAsync()).ReturnsAsync(response.Object);

                var reader = new ApiReader(defaultConfig, client.Object);
                try
                {
                    string token = await reader.SendTokenRequest();
                    token.Should().Be("TOKENGOESHERE");
                }
                catch
                {
                    Assert.Fail();
                }
            }).GetAwaiter().GetResult();
        }
Example #8
0
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        static void Main(string[] args)
        {
            APR = new ApiReader();         // Initialises ApiReader
            DBC = new DatabaseConnector(); // Initialises DatabaseConnector

            ANN = new NeuralNetwork();

            ANN.ImportWeights(ReadWeights());

            List <DatabaseRow> rows = DBC.SelectAllFromDatabase();

            //ANN.TimeNetwork(rows);

            ANN.TrainNetwork(rows, 10000);

            List <double> weights = new List <double>();

            for (int i = 0; i < ANN.Synapses.Count; i++)
            {
                weights.Add(ANN.Synapses[i].Weight);
            }

            WriteWeights(weights);

            double output = TestNetwork(rows, 1);

            Console.ReadLine();
        }
Example #9
0
        static void Main(string[] args)
        {
            FileReader     fileReader     = new FileReader();
            Meteorologist  meteorologist  = new Meteorologist();
            WeatherResults weatherResults = new WeatherResults();
            ApiReader      apiReader      = new ApiReader();

            //Console.WriteLine("Hello! Please write the file where your temperature data is stored and separator in the file seperated with a ','.");
            //string input = Console.ReadLine();
            //string[] userInput = input.Split(',');

            //List<TemperatureData> temperatureList = fileReader.CSVReader(userInput[0], Convert.ToChar(userInput[1]));

            //weatherResults.WarmestDataEntry = meteorologist.GetWarmestTemperature(temperatureList);
            //weatherResults.FirstSubZeroEntry = meteorologist.GetFirstBelowZero(temperatureList);
            //weatherResults.MeanValues = meteorologist.GetMeanTemperature(temperatureList);
            //weatherResults.ColdestDataEntry = meteorologist.GetColdestTemperature(temperatureList);

            //Console.WriteLine(weatherResults.GetWeatherResult(temperatureList[0].TimeStamp, temperatureList[temperatureList.Count() - 1].TimeStamp));

            var    apiString         = $"https://opendata-download-metobs.smhi.se/api/version/latest/parameter/1.json";
            var    response          = apiReader.GetAsyncFromApi(apiString);
            var    simpleStationList = fileReader.ReadAirTempRespons(response).GetAwaiter().GetResult();
            string stationJsonArray  = JsonConvert.SerializeObject(simpleStationList);

            System.IO.File.WriteAllText(@"C:\Users\li.wirstrom\Documents\Code is King\FFCG.CodeIsKing\Meteorologist\src\stations.json", stationJsonArray);
        }
        ApiReader CreateApiReader(string relativeUrl)
        {
            var reader = new ApiReader(relativeUrl, "");

            reader.BaseUri = new Uri(API_URL);
            return(reader);
        }
Example #11
0
        private static async Task WritePublicApi(PublicApiWriter publicApiWriter, PrinterConfig printerConfig, string solutionOrProjectFilePath, string humanReadableFileName, string jsonFileName, CancellationToken cancellationToken)
        {
            var solutionNodes = await ApiReader.ReadApiFromProjects(solutionOrProjectFilePath, cancellationToken);

            var filteredNodes      = FilteredApiNode.For(printerConfig, solutionNodes).ToList();
            var writeHumanReadable = publicApiWriter.WriteHumanReadable(filteredNodes, new FileInfo(humanReadableFileName), cancellationToken);

            JsonSerialization.WriteJson(filteredNodes, new FileInfo(jsonFileName));
            await writeHumanReadable;
        }
Example #12
0
        public void CanSortPetsIntoCategoriesWithoutError()
        {
            var pets = ApiReader.GetAvailablePets();

            Assert.IsTrue(pets != null);
            Assert.IsTrue(pets.Length > 0);

            var categories = pets.SortPetsByCategory();

            Assert.IsTrue(categories != null);
            Assert.IsTrue(categories.Count > 0);
        }
        public async Task DeleteLead()
        {
            var reader = CreateApiReader("leads");

            // use API key with full permissions (Module = CS.GENERIC)
            reader.ApiKey = YOURAPIKEY_FULLACCESS;
            var oDataFilter = ApiReader.BuildFilter("Email eq {0}", TEST_NONEXISTENT_EMAIL);

            foreach (var obj in await reader.QueryListByFilter <ApiLeadReadFromDatabase>(oDataFilter))
            {
                await reader.Delete(obj.LeadID);
            }
        }
Example #14
0
 public static async Task TestErrorReport()
 {
     var url = "http://localhost:26316/api/ErrorReport";
     var r   = new ApiReader(url, "");
     {
         await r.PostFile("",
                          new KeyValuePair <string, string>[]
         {
             new KeyValuePair <string, string>("sourceObjectTypeId", "1")
         }, new byte[] { 1 }, "file", "attachment.zip"
                          );
     }
 }
Example #15
0
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        public static void Main()
        {
            APR = new ApiReader();                                                 // Initialises ApiReader
            DBC = new DatabaseConnector();                                         // Initialises DatabaseConnector

            currency = new CurrencyPair(2, 1);                                     // Creates new currency pair of ETH/BTC

            _timer          = new Timer(10 * 1000);                                // Create timer to run every 10 seconds
            _timer.Elapsed += new System.Timers.ElapsedEventHandler(TimerElapsed); // Sets method to be run when the timer is elapsed
            _timer.Start();                                                        // Starts the timer

            Console.ReadLine();
        }
Example #16
0
        private IReadOnlyCollection <IApiNode> ReadApi()
        {
            try
            {
                return(ApiReader.ReadApiFromProjects(m_ThisProjectFile.FullName, CancellationToken.None).GetAwaiter()
                       .GetResult());
            }
            catch (ReflectionTypeLoadException typeLoadException) when(typeLoadException.LoaderExceptions.Any())
            {
                string message = typeLoadException.Message + "\r\nLoaderExceptions:\r\n" +
                                 string.Join("\r\n", typeLoadException.LoaderExceptions.Select(x => x.Message));

                throw new ReflectionTypeLoadException(typeLoadException.Types, typeLoadException.LoaderExceptions,
                                                      message);
            }
        }
        public async Task QueryAllLeads()
        {
            var reader = CreateApiReader("leads");

            // use API key with full permissions (Module = CS.GENERIC)
            reader.ApiKey = YOURAPIKEY_FULLACCESS;
            var queryAllLeads = (await reader.QueryList <ApiLeadReadFromDatabase>()).ToArray();

            var leadWithAtLeastOneCustomField = queryAllLeads.FirstOrDefault(l => l.Custom != null && l.Custom.Length > 0);
            // or
            var oDataFilter = ApiReader.BuildFilter("FirstName eq {0}", "Stan");
            var queryLeadsWhoseFirstNameIsStan = reader.QueryListByFilter <ApiLeadReadFromDatabase>(oDataFilter);

            // you can view result in browser by pasting this url
            Console.WriteLine(reader.LastUrlUsedToQuery);
        }
        public void Run()
        {
            var shippedLines = File.ReadAllLines(ApiShippedFile);
            var builder      = new StringBuilder();
            var reader       = new ApiReader(new FileInfo(AssemblyFile));

            foreach (var api in reader.Read())
            {
                if (!shippedLines.Contains(api))
                {
                    builder.AppendLine(api);
                }
            }
            var unshippedApis = builder.ToString();

            File.WriteAllText(ApiShippedFile, unshippedApis);
        }
        public void GetAsync_ShouldThrowIfInvalidTest()
        {
            Task.Run(async() =>
            {
                try
                {
                    var reader = new ApiReader();
                    // reader has no configuration nor token

                    await reader.GetAsync <object>("anyquery");
                    Assert.Fail();
                }
                catch
                {
                }
            }).GetAwaiter().GetResult();
        }
Example #20
0
        public void OnHttpRequest(ApiReader reader, ApiResponse response)
        {
            IEnumerable <string> values;

            if (response.Headers.TryGetValues("X-Apikey-Quota-Allotted", out values))
            {
                if (Int32.TryParse(values.First(), out quotaAllotted))
                {
                    //it worked
                }
            }

            if (response.Headers.TryGetValues("X-Apikey-Quota-Current", out values))
            {
                if (Int32.TryParse(values.First(), out currentRateCounter))
                {
                    //it worked
                }
            }
        }
        public async Task TestAddresses()
        {
            var reader = CreateApiReader("accountaddresses");

            reader.ApiKey = YOURAPIKEY_FULLACCESS;
            // check existing addresses
            var allAddresses = await reader.QueryList <ApiAccountAddress>();

            // if we do not have an address, create one

            if (!(await reader.QueryListByFilter <ApiAccountAddress>(ApiReader.BuildFilter("AccountId eq {0}", testAccountId))).Any())
            {
                // an address is separate object and it has its own ID: BranchID
                // however, BranchId will be phased out

                // you should use AccountId instead.


                var newAddress = new ApiAccountAddress();
                // make sure you specify valid AccountId
                newAddress.AccountId = testAccountId;
                newAddress.Address1  = "123 Main Street";
                newAddress.City      = "New York";
                newAddress.Country   = "US";
                await reader.Post(newAddress);

                // to update address, also use specify valid AccountId; remove BranchId from ApiAccountAddress object.
                var postAddress = new ApiAccountAddress();
                postAddress.AccountId = testAccountId;
                postAddress.Address1  = "Another address";
                await reader.Put(testAccountId, postAddress);
            }

            // delete


            await reader.Delete(testAccountId);
        }
        public void SendTokenRequest_ShouldThrowWhenNotSuccessful()
        {
            Task.Run(async() =>
            {
                var client   = new Mock <IWebClient>();
                var response = new Mock <IApiResponse>();
                response.Setup(i => i.IsSuccessful()).Returns(false);

                client.Setup(i => i.RequestAccessTokenAsync()).ReturnsAsync(response.Object);
                var reader = new ApiReader(defaultConfig, client.Object);
                try
                {
                    await reader.SendTokenRequest();
                    Assert.Fail();
                }
                catch (HttpRequestException ex)
                {
                }
                catch
                {
                    Assert.Fail();
                }
            }).GetAwaiter().GetResult();
        }
Example #23
0
 public WorldOfWarcraftApi(ApiReader apiReader)
 {
     reader = apiReader;
 }
 public Starcraft2Api(ApiReader apiReader)
 {
     reader = apiReader;
 }
Example #25
0
 public DiabloApi(ApiConfiguration configuration)
 {
     reader = new ApiReader(configuration);
 }
Example #26
0
 public DiabloApi()
 {
     reader = new ApiReader();
 }
Example #27
0
 public void OnHttpRequest(ApiReader reader, IApiResponse response)
 {
     throw new NotImplementedException();
 }
 public WorldOfWarcraftApi(ApiConfiguration configuration)
 {
     reader = new ApiReader(configuration);
 }
 public WorldOfWarcraftApi()
 {
     reader = new ApiReader();
 }
Example #30
0
 public void TradingLib_ApiReader_DownloadStringTest()
 {
     Assert.AreEqual(ApiReader.DownloadString("https://example.com/"),
                     "<!doctype html>\n<html>\n<head>\n    <title>Example Domain</title>\n\n    <meta charset=\"utf-8\" />\n    <meta http-equiv=\"Content-type\" content=\"text/html; charset=utf-8\" />\n    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n    <style type=\"text/css\">\n    body {\n        background-color: #f0f0f2;\n        margin: 0;\n        padding: 0;\n        font-family: \"Open Sans\", \"Helvetica Neue\", Helvetica, Arial, sans-serif;\n        \n    }\n    div {\n        width: 600px;\n        margin: 5em auto;\n        padding: 50px;\n        background-color: #fff;\n        border-radius: 1em;\n    }\n    a:link, a:visited {\n        color: #38488f;\n        text-decoration: none;\n    }\n    @media (max-width: 700px) {\n        body {\n            background-color: #fff;\n        }\n        div {\n            width: auto;\n            margin: 0 auto;\n            border-radius: 0;\n            padding: 1em;\n        }\n    }\n    </style>    \n</head>\n\n<body>\n<div>\n    <h1>Example Domain</h1>\n    <p>This domain is established to be used for illustrative examples in documents. You may use this\n    domain in examples without prior coordination or asking for permission.</p>\n    <p><a href=\"http://www.iana.org/domains/example\">More information...</a></p>\n</div>\n</body>\n</html>\n");
 }