private static void Main(string[] args)
        {
            try
            {
                Console.WriteLine(StringHelper.input_console_string);
                int distance;

                while (!int.TryParse(Console.ReadLine(), out distance))
                {
                    Console.WriteLine(StringHelper.incorrectInputValue);
                    Console.WriteLine(StringHelper.input_console_string);
                }

                Console.WriteLine(StringHelper.gettingData);
                var api        = new ExternalApi(new System.Net.Http.HttpClient());
                var ships      = api.GetAllShips();
                var calculator = new Calculator();

                foreach (var item in ships)
                {
                    var countStop = calculator.CalculateStops(item.MGLT, item.consumables, distance);

                    Console.WriteLine(item.name + ": " + countStop);
                }
                Console.Read();
            }
            catch (Exception ex)
            {
                Console.WriteLine("Something went wrong : " + Environment.NewLine + " -      Internet might not be available." + Environment.NewLine + " -      The WEB API (" + StringHelper.urlbase + ") might be down.");

                Console.Read();
            }
        }
Beispiel #2
0
        public void TestExternalApi()
        {
            ExternalApi ExtApi = new ExternalApi();
            int         res    = ExtApi.GetValue(10);

            Assert.IsTrue(res == 40);
        }
Beispiel #3
0
        public void TestAddAsync_ServerAccepts_ReturnsExternalApi()
        {
            var header = new ExternalApiHeader
            {
                Name  = "Header",
                Value = "Api header"
            };
            var externalApi = new ExternalApi
            {
                Name        = "New ExternalApi",
                Description = "New Description",
                Headers     = new List <ExternalApiHeader>
                {
                    header
                }
            };
            var mockedNfieldConnection = new Mock <INfieldConnectionClient>();
            var mockedHttpClient       = CreateHttpClientMock(mockedNfieldConnection);
            var content = new StringContent(JsonConvert.SerializeObject(externalApi));

            mockedHttpClient
            .Setup(client => client.PostAsJsonAsync(new Uri(ServiceAddress, "externalapis/"), externalApi))
            .Returns(CreateTask(HttpStatusCode.OK, content));

            var target = new NfieldExternalApisService();

            target.InitializeNfieldConnection(mockedNfieldConnection.Object);

            var actual = target.AddAsync(externalApi).Result;

            Assert.Equal(externalApi.Name, actual.Name);
            Assert.Equal(externalApi.Description, actual.Description);
            Assert.Equal(externalApi.Headers.First().Name, header.Name);
            Assert.Equal(externalApi.Headers.First().Value, header.Value);
        }
Beispiel #4
0
        public async Task <IActionResult> Get(
            [FromServices] ExternalApi XApi,
            CancellationToken token)
        {
            var ret = await XApi.GetForumSummaryAsync(token);

            return(Result(ret));
        }
        public void GetAllShips_returnsList()
        {
            var api     = new ExternalApi(new HttpClient());
            var results = api.GetAllShips();

            Assert.IsNotNull(results);
            Assert.IsTrue(results[0].MGLT != string.Empty);
        }
Beispiel #6
0
 public async Task <IActionResult> GetResolution(
     [FromServices] ExternalApi XApi,
     string problemId,
     int?page,
     CancellationToken token)
 {
     return(Json(await XApi.GetProblemResolutionsAsync(problemId, page.HasValue ? page.Value : 1, token)));
 }
Beispiel #7
0
 public async Task <IActionResult> GetBlogUrl(
     [FromServices] ExternalApi XApi,
     string username,
     CancellationToken token
     )
 {
     return(Result(await XApi.GetUserBlogDomainAsync(username, token)));
 }
Beispiel #8
0
 public async Task <IActionResult> GetBlogPosts(
     [FromServices] ExternalApi XApi,
     string username,
     CancellationToken token
     )
 {
     return(Json(await XApi.GetUserResolutionsAsync(username, 1, token)));
 }
Beispiel #9
0
        public ExternalApiBaseUnit()
        {
            var cultureInfo = new CultureInfo("en-GB");

            cultureInfo.NumberFormat.CurrencySymbol   = "£";
            CultureInfo.DefaultThreadCurrentCulture   = cultureInfo;
            CultureInfo.DefaultThreadCurrentUICulture = cultureInfo;
            Api = new ExternalApi();
        }
        /// <summary>
        /// See <see cref="INfieldExternalApisService.RemoveAsync"/>
        /// </summary>
        public Task RemoveAsync(ExternalApi externalApi)
        {
            if (externalApi == null)
            {
                throw new ArgumentNullException("externalApi");
            }

            return
                (Client.DeleteAsync(new Uri(ExternalApisApi, externalApi.Name))
                 .FlattenExceptions());
        }
Beispiel #11
0
        public async Task <QueryResult> Handle(Query query)
        {
            var result = new QueryResult();

            if (!Storage.ContainsShows())
            {
                await ExternalApi.StoreShows();
            }
            result = Storage.GetShows(query);
            return(result);
        }
        /// <summary>
        /// See <see cref="INfieldExternalApisService.UpdateAsync"/>
        /// </summary>
        public Task <ExternalApi> UpdateAsync(ExternalApi externalApi)
        {
            if (externalApi == null)
            {
                throw new ArgumentNullException("externalApi");
            }

            return(Client.PutAsJsonAsync(ExternalApisApi, externalApi)
                   .ContinueWith(task => task.Result.Content.ReadAsStringAsync().Result)
                   .ContinueWith(task => JsonConvert.DeserializeObject <ExternalApi>(task.Result))
                   .FlattenExceptions());
        }
 public HorizonRESTClient(string BaseURL)
 {
     BaseURI                      = new Uri(BaseURL);
     ClientConfiguration          = new Configuration();
     ClientConfiguration.BasePath = BaseURI.AbsoluteUri;
     Authentication               = new AuthApi(ClientConfiguration);
     Configuration                = new ConfigApi(ClientConfiguration);
     Entitlements                 = new EntitlementsApi(ClientConfiguration);
     External                     = new ExternalApi(ClientConfiguration);
     Inventory                    = new InventoryApi(ClientConfiguration);
     Monitoring                   = new MonitorApi(ClientConfiguration);
 }
        public HttpClient GetHttpClient(ExternalApi externalApi, ExternalApiAuth externalApiAuth)
        {
            var client = new HttpClient
            {
                BaseAddress = new Uri(externalApi.BaseUrl)
            };
            var byteArray = Encoding.ASCII.GetBytes(string.Format("{0}:{1}", externalApiAuth.Token, externalApiAuth.Key));

            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            return(client);
        }
Beispiel #15
0
 private void Tick(object state)
 {
     try
     {
         var api        = new ExternalApi();
         var updateList = api.FetchDataFromExternalApi().Result;
         if (updateList != null)
         {
             _companyRepository.MergeUpdateList(updateList).Wait();
         }
     }
     finally
     {
         _timer?.Change(Interval, Timeout.Infinite);
     }
 }
Beispiel #16
0
        // GET api/values/5
        public string GetValue(int currentValue)
        {
            CalculateValue CalcVal = new CalculateValue();

            currentValue = CalcVal.Calc(currentValue);

            ExternalApi ExtApi = new ExternalApi();

            currentValue = ExtApi.GetValue(currentValue);

            Value vl = new Value();

            vl.value = currentValue;
            repo.Create(vl);
            repo.Save();
            //db.Values.Add(vl);
            //db.SaveChanges();
            return(currentValue.ToString());
        }
Beispiel #17
0
        public SchoologyAPICall()
        {
            using (WebhostEntities db = new WebhostEntities())
            {
                ExternalApi schoology = db.ExternalApis.Where(api => api.service.Equals("Schoology")).Single();
                BaseUrl               = schoology.BaseUrl;
                oauth_consumer_key    = schoology.ClientId;
                oauth_consumer_secret = schoology.ClientSecret;

                client = new RestClient(BaseUrl);

                foreach (ApiRequestHeader header in schoology.ApiRequestHeaders)
                {
                    client.AddDefaultHeader(header.Name, header.Value);
                }

                client.AddDefaultHeader("Authorization", AuthorizationHeaderValue);
            }
        }
Beispiel #18
0
        public void TestRemoveAsync_ServerRemovedExternalApi_DoesNotThrow()
        {
            const string ExternalApiName = "ApiToDelete";
            var          externalApi     = new ExternalApi {
                Name = ExternalApiName
            };
            var mockedNfieldConnection = new Mock <INfieldConnectionClient>();
            var mockedHttpClient       = CreateHttpClientMock(mockedNfieldConnection);

            mockedHttpClient
            .Setup(client => client.DeleteAsync(new Uri(ServiceAddress, "externalapis/" + ExternalApiName)))
            .Returns(CreateTask(HttpStatusCode.OK));

            var target = new NfieldExternalApisService();

            target.InitializeNfieldConnection(mockedNfieldConnection.Object);

            // assert: no throw
            target.RemoveAsync(externalApi).Wait();
        }
Beispiel #19
0
        /// <summary>
        /// Set the credential to have access to only the scopes that you need and the user you wish to impersonate.
        /// Adminj is the owner of all relevant domain level items.
        /// </summary>
        /// <param name="scopes"></param>
        /// <param name="userToImpersonate"></param>
        public void SetCredential(String[] scopes, String userToImpersonate = "adminj")
        {
            using (WebhostEntities db = new WebhostEntities())
            {
                ExternalApi    gapi = db.ExternalApis.Where(api => api.service.Equals("Google")).Single();
                ServiceAccount acct = gapi.ServiceAccounts.Where(a => a.Password.Equals("cert")).Single();
                State.log.WriteLine("Got API info from Webhost database.");

                // It is important that this be initiallized with the correct ServiceAccount Email address associated with the Security Certificate.
                // Otherwise your requests are rejected.
                credential = new ServiceAccountCredential(new ServiceAccountCredential.Initializer(acct.Account)
                {
                    User   = String.Format("{0}@dublinschool.org", userToImpersonate),
                    Scopes = scopes
                             //This is the list of APIs that we want to be able to access.  Currently only care about Users.
                }.FromCertificate(cert));

                State.log.WriteLine("Credential Recieved.  Connecting service.");
                WebhostEventLog.GoogleLog.LogInformation("Got credentials accepted for impersonating {0}@dublinschool.org.", userToImpersonate);
            }
        }
Beispiel #20
0
 private static void PopulateDb(IHost host)
 {
     using (var scope = host.Services.CreateScope())
     {
         var services = scope.ServiceProvider;
         try
         {
             var companyRepository = services.GetRequiredService <ICompanyRepository>();
             var api        = new ExternalApi();
             var updateList = api.FetchDataFromExternalApi().Result;
             if (updateList != null)
             {
                 companyRepository.MergeUpdateList(updateList).Wait();
             }
         }
         catch (Exception ex)
         {
             var logger = services.GetRequiredService <ILogger <Program> >();
             logger.LogError(ex, "An error occurred populating the DB.");
         }
     }
 }
Beispiel #21
0
        public void TestUpdateAsync_ExternalApiExists_ReturnsExternalApi()
        {
            const string externalApiName = "ApiToUpdate";
            var          externalApi     = new ExternalApi
            {
                Name        = externalApiName,
                Description = "updated description"
            };
            var mockedNfieldConnection = new Mock <INfieldConnectionClient>();
            var mockedHttpClient       = CreateHttpClientMock(mockedNfieldConnection);

            mockedHttpClient
            .Setup(client => client.PutAsJsonAsync(new Uri(ServiceAddress, "externalapis/"), externalApi))
            .Returns(CreateTask(HttpStatusCode.OK, new StringContent(JsonConvert.SerializeObject(externalApi))));

            var target = new NfieldExternalApisService();

            target.InitializeNfieldConnection(mockedNfieldConnection.Object);

            var actual = target.UpdateAsync(externalApi).Result;

            Assert.Equal(externalApi.Description, actual.Description);
        }
        public ActionResult <List <ExternalApi> > Get()
        {
            List <Tool>    tools      = _toolService.Get();
            List <History> allHistory = _historyService.Get();
            List <History> history    = new List <History>();

            foreach (var lend in allHistory)
            {
                if (lend.createTime == lend.lendTime)
                {
                    history.Add(lend);
                }
            }

            DateTime           date   = DateTime.Now;
            List <ExternalApi> result = new List <ExternalApi>();

            foreach (var tool in tools)
            {
                ExternalApi temp = new ExternalApi();
                temp.toolName = tool.toolName;
                temp.room     = tool.room;
                temp.maxCount = tool.maxCount;
                var            nEquipment = tool.maxCount;
                List <History> isLend     = new List <History>();


                for (var item = 1; item < history.Count; item++)
                {
                    if (DateTime.Compare(history[item].rentTime.AddMinutes(70), DateTime.Now) < 0)
                    {
                        nEquipment--;
                    }
                }
                // Console.WriteLine(nEquipment);
                int[] nInEachTime = { nEquipment, nEquipment, nEquipment, nEquipment, nEquipment, nEquipment };
                for (var i = 0; i < nInEachTime.Length; i++)
                {
                    if (i > 2)
                    {
                        foreach (var j in history)
                        {
                            if (DateTime.Compare(j.rentTime, history[0].rentTime.AddHours(10 + i).AddMinutes(30)) == 0)
                            {
                                nInEachTime[i]--;
                            }
                        }
                    }
                    else
                    {
                        foreach (var j in history)
                        {
                            if (DateTime.Compare(j.rentTime, history[0].rentTime.AddHours(9 + i).AddMinutes(30)) == 0)
                            {
                                nInEachTime[i]--;
                            }
                        }
                    }
                }
                temp.slot1 = nInEachTime[0];
                temp.slot2 = nInEachTime[1];
                temp.slot3 = nInEachTime[2];
                temp.slot4 = nInEachTime[3];
                temp.slot5 = nInEachTime[4];
                temp.slot6 = nInEachTime[5];
                result.Add(temp);
            }

            return(Ok(result));
        }
Beispiel #23
0
 public Adapter(ExternalApi api)
 {
     _api = api;
 }
 public QuestionnaireService(ILogger <QuestionnaireService> logger, IOptions <ExternalApi> externalApi)
 {
     _externalApi = externalApi.Value;
     _logger      = logger;
 }
Beispiel #25
0
        public void CanSaveBalance_BalanceLessThan100000_ReturnsFalse()
        {
            var externalApi = new ExternalApi();

            Assert.IsFalse(externalApi.CheckAccountBalance(100, AccountType.Bronze));
        }
Beispiel #26
0
        public void CanSaveBalance_GoldAccountTypeBalanceGreaterThan100000_ReturnsTrue()
        {
            var externalApi = new ExternalApi();

            Assert.IsTrue(externalApi.CheckAccountBalance(100001, AccountType.Gold));
        }
Beispiel #27
0
        public void CanSaveBalance_GoldAccountType_ReturnsFalse()
        {
            var externalApi = new ExternalApi();

            Assert.IsFalse(externalApi.CheckAccountBalance(100000, AccountType.Gold));
        }
Beispiel #28
0
 public WhaleHotlineHandle()
 {
     _whaleHotlineApi = new ExternalApi("http://hotline.whalemuseum.org");
 }
        public void GetAllShips_2Async()
        {
            try
            {
                var handlerMock = new Mock <HttpMessageHandler>(MockBehavior.Strict);
                handlerMock
                .Protected()
                .Setup <Task <HttpResponseMessage> >(
                    "SendAsync",
                    ItExpr.IsAny <HttpRequestMessage>(),
                    ItExpr.IsAny <CancellationToken>()
                    )
                .ReturnsAsync(new HttpResponseMessage()
                {
                    StatusCode = HttpStatusCode.OK,
                    Content    = new StringContent("{'count': 37,'next': null,'previous': null, 'results': [{ " +
                                                   "'name': 'Executor','model': 'Executor-class star dreadnought','manufacturer': 'Kuat Drive Yards, Fondor Shipyards','cost_in_credits': '1143350000', " +
                                                   "'length': '19000','max_atmosphering_speed': 'n/a','crew': '279144','passengers': '38000','cargo_capacity': '250000000','consumables': '6 years','hyperdrive_rating': '2.0'," +
                                                   "'MGLT': '40','starship_class': 'Star dreadnought','pilots': [],'films': ['https://swapi.co/api/films/2/','https://swapi.co/api/films/3/'],'created': '2014-12-15T12:31:42.547000Z'," +
                                                   "'edited': '2017-04-19T10:56:06.685592Z','url': 'https://swapi.co/api/starships/15/'}]}", Encoding.UTF8, "application/json"),
                })
                .Verifiable();

                // use real http client with mocked handler here
                var httpClient = new HttpClient(handlerMock.Object)
                {
                    BaseAddress = new Uri(StringHelper.urlbase),
                };

                var subjectUnderTest = new ExternalApi(httpClient);

                var result = subjectUnderTest
                             .GetAllShips();

                // ASSERT
                Assert.IsNotNull(result);
                Assert.AreEqual(result[0].name, "Executor");
                Assert.AreEqual(result[0].MGLT, "40");
                Assert.AreEqual(result[0].model, "Executor-class star dreadnought");
                Assert.AreEqual(result[0].manufacturer, "Kuat Drive Yards, Fondor Shipyards");
                Assert.AreEqual(result[0].cargo_capacity, "250000000");
                Assert.AreEqual(result[0].consumables, "6 years");


                // also check the 'http' call was like we expected it
                var expectedUri = new Uri(StringHelper.urlbase + StringHelper.getStarships);

                handlerMock.Protected().Verify(
                    "SendAsync",
                    Times.Exactly(1), // we expected a single external request
                    ItExpr.Is <HttpRequestMessage>(req =>
                                                   req.Method == HttpMethod.Get && // we expected a GET request
                                                   req.RequestUri == expectedUri // to this uri
                                                   ),
                    ItExpr.IsAny <CancellationToken>()
                    );
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Beispiel #30
0
 public OpenSkyHandle()
 {
     _openSkyApi = new ExternalApi("https://opensky-network.org/api");
 }