예제 #1
0
파일: JokAPI.cs 프로젝트: jokio/jok-play
        public static GameFinishResult FinishGame(bool? isFullGame, bool? isDraw, string channel, params GameFinishPlayerInfo[] playerInfos)
        {
            try
            {
                if (GameID == null || GameSecret == null)
                    new GameFinishResult { Error = new Exception("Please set GameID & GameSecret") };

                var gameInfo = new GameFinishInfo
                {
                    GameID = GameID.Value,
                    GameSecret = GameSecret,
                    IsFull = isFullGame,
                    IsDraw = isDraw,
                    Channel = channel,
                    Players = playerInfos.ToList()
                };

                var url = String.Format(FinishGameUrl, GameID);
                var postTask = new HttpClient().PostAsJsonAsync<GameFinishInfo>(url, gameInfo);
                postTask.Wait();

                if (postTask.IsCompleted && postTask.Result.StatusCode == System.Net.HttpStatusCode.OK)
                {
                    var resultTask = postTask.Result.Content.ReadAsAsync<GameFinishResult>();
                    resultTask.Wait();

                    if (!resultTask.IsCompleted)
                    {
                        return new GameFinishResult { Error = resultTask.Exception };
                    }

                    return resultTask.Result;
                }

                return new GameFinishResult { Error = postTask.Exception };
            }
            catch (Exception ex)
            {
                return new GameFinishResult { Error = ex };
            }
        }
예제 #2
0
파일: Song.cs 프로젝트: alexandercessac/Lib
        /// <summary>
        /// Get data in this.Url and use <paramref name="fileWriter"/> to save to disk
        /// </summary>
        /// <param name="fileWriter"></param>
        /// <returns>Task that completes when file is written to disk</returns>
        public Task<string> Download(IFileWriter fileWriter)
        {
            var tId = Thread.CurrentThread.ManagedThreadId;

            try
            {
                var contentsTask = new HttpClient().GetStringAsync(Url);

                //Block current thread until contentsTask is complete
                contentsTask.Wait();

                //Return task that will write the contents to disk
                return fileWriter.WriteFile(contentsTask.Result, Name);
            }
            catch
            {
                //Return a sucessfully completed Task<string> with the below result
                return Task.FromResult(string.Format("Failed to download: {0}", Url));
            }

        }
예제 #3
0
        /// <summary>
        /// Shortens a url
        /// </summary>
        /// <param name="url">Url to shorten</param>
        /// <returns>The id of the shortened url</returns>
        public async Task<int> ShortenUrlAsync(string url)
        {
            url = DefaultToHttpsProtocol(url);
            var uri = new Uri(url, UriKind.RelativeOrAbsolute);
            var request = new HttpClient().GetAsync(uri.ToString());

            var shortUrl = ShortenedUrls.Create();
            shortUrl.Created = DateTime.UtcNow;
            shortUrl.Url = uri.ToString();
            ShortenedUrls.Add(shortUrl);

            if (request.Wait(2000))
            {
                shortUrl.HttpStatusCode = (int)request.Result.StatusCode;
                if (request.Result.IsSuccessStatusCode)
                {
                    var response = await request.Result.Content.ReadAsStringAsync();
                    shortUrl.Title = GetTitle(response);
                }
            }

            await SaveChangesAsync();
            return shortUrl.Id;
        }
예제 #4
0
        public void FakeServer_IgnoredParameter_Returns200()
        {
            var expectedResult = new { ResourceId = 1234 };
            const string baseAddress = "http://localhost:12354";

            const string fakeurl = "/some-resource/{ignore}/some-resource?date={ignore}&type={ignore}";
            const string actualurl = "/some-resource/1234/some-resource?date=2015-02-06T09:52:10&type=1";

            using (var fakeServer = new FakeServer(12354))
            {
                fakeServer.Expect.Get(fakeurl).Returns(HttpStatusCode.Accepted, expectedResult);
                fakeServer.Start();

                var t = new HttpClient().GetAsync(new Uri(baseAddress + actualurl));
                t.Wait();
                var result = t.Result;

                result.StatusCode.Should().Be(HttpStatusCode.Accepted);
            }
        }
예제 #5
0
        public void FakeServer_ExpectPutWithObjectBodyReturns201_Returns201()
        {
            var expectedResult = new {RestaurantId = 1234};
            const string baseAddress = "http://localhost:12354";

            const string url = "/some-url";

            using (var fakeServer = new FakeServer(12354))
            {
                fakeServer.Expect.Put(url, string.Empty).Returns(HttpStatusCode.Created, expectedResult);
                fakeServer.Start();

                var t = new HttpClient().PutAsync(new Uri(baseAddress + url), new StringContent(String.Empty));
                t.Wait();
                var result = t.Result;

                result.StatusCode.Should().Be(HttpStatusCode.Created);
            }
        }
예제 #6
0
        public void FakeServer_ExpectPutWithComplexBodyReturnsComplexObject()
        {
            const string expectedResult = "{\"Complex\":{\"Property1\":1,\"Property2\":true}}";
            const string body = "{\"Complex\":1}";

            using (var fakeServer = new FakeServer(12354))
            {
                fakeServer.Expect.Put("/some-url", body).Returns(HttpStatusCode.Created, expectedResult);
                fakeServer.Start();

                var t = new HttpClient().PutAsync(new Uri("http://localhost:12354" + "/some-url"), new StringContent(body));
                t.Wait();
                var result = t.Result;

                var resultTask = result.Content.ReadAsStringAsync();
                resultTask.Wait();

                result.StatusCode.Should().Be(HttpStatusCode.Created);
                resultTask.Result.Should().Be(expectedResult);
            }
        }
예제 #7
0
        public void FakeServer_ExpectGetToAnEndpointWithAFiveSecondResponseTime_ResponseTimeIsGreaterThanFiveSeconds()
        {
            var expectedResult = new { ResourceId = 1234 };
            const string baseAddress = "http://localhost:12354";
            var expectedResponseTime = TimeSpan.FromSeconds(5);

            const string fakeurl = "/some-url";

            using (var fakeServer = new FakeServer(12354))
            {
                fakeServer.Expect.ResponseTime = expectedResponseTime;
                fakeServer.Expect.Get(fakeurl).Returns(HttpStatusCode.OK, expectedResult);
                fakeServer.Start();

                var stopwatch = Stopwatch.StartNew();

                var t = new HttpClient().GetAsync(new Uri(baseAddress) + fakeurl);
                t.Wait();

                stopwatch.Stop();

                stopwatch.Elapsed.Should().BeGreaterOrEqualTo(expectedResponseTime);
            }
        }
예제 #8
0
    public bool updateData() {
      SQLiteConnection connection = DependencyService.Get<IDatabaseHandler>().getDBConnection();
      Info cacheInfo = connection.Table<Info>().Where(i => i.key.Equals("eventCacheTime")).FirstOrDefault();
      long lastCacheTime = cacheInfo.value;
      long currentTime = (long)(DateTime.Now - new DateTime(1970, 1, 1)).TotalMilliseconds;

      if (currentTime - lastCacheTime > 1000 * 60 * 60 * 6) {
        string html;

        Task<string> task = new HttpClient().GetStringAsync(new Uri("http://harrisburg.psu.edu/calendar"));
        task.Wait();
        html = task.Result;

        for (int i = 1; i < 9; i++) {
          Task<string> task2 = new HttpClient().GetStringAsync(new Uri("http://harrisburg.psu.edu/calendar?page=" + i));
          task2.Wait();
          html += task2.Result;
        }

        string regex = @"views-row-\d.*?<span class=""date-display-start""><span>(\w{3})\s(\d{4}).*?<\/time>\s*(<span class=""separator"">.*?<div class=""clr""><\/div>|<div class=""clr""><\/div>)<\/span>.*?<span class=""field-content""><a href=""([\/\w\d\-]*)"">(.*?)<\/a><\/span>";

        List<Event> events = new List<Event>();
        MatchCollection matches = Regex.Matches(html, regex, RegexOptions.Singleline);

        foreach (Match m in matches) {
          Event e = new Event(System.Net.WebUtility.HtmlDecode(m.Groups[5].Value), m.Groups[1].Value, m.Groups[2].Value, "http://harrisburg.psu.edu" + m.Groups[4].Value);

          if (!events.Contains(e))
            events.Add(e);
        }

        connection.BeginTransaction();
        connection.DeleteAll<Event>();

        foreach (Event e in events) {
          connection.Insert(e);
        }

        cacheInfo.value = currentTime; //Not entirely accurate, but will work alright
        connection.Update(cacheInfo);
        connection.Commit();
        connection.Close();
        updateData();

      } else if (event_picker.Items.Count == 0) {

        var eventEntries = connection.Table<Event>();

        event_picker.Items.Clear();

        foreach (var e in eventEntries) {
          string month = e.month + " " + e.year;

          if (!event_picker.Items.Contains(month))
            event_picker.Items.Add(month);
        }

        connection.Close();

        string now = numberToMonth(DateTime.Now.Month) + " " + DateTime.Now.Year;

        for (int i = 0; i < event_picker.Items.Count; i++) {
          if (event_picker.Items[i].Equals(now)) {
            event_picker.SelectedIndex = i;
            break;
          }
        }

        if (event_picker.SelectedIndex == -1 && event_picker.Items.Count > 0)
          event_picker.SelectedIndex = 0;
      }

      return false;
    }
        public void SendAsync_ServiceModel_Throws_When_StreamContent_Throws(string uri, TransferMode transferMode)
        {
            // Arrange
            server = CreateServer(transferMode);
            Task task = new HttpClient().GetAsync(BaseUri(transferMode) + uri);

            // Act & Assert
            Assert.Throws<HttpRequestException>(() => task.Wait());
        }
        public void SendAsync_ServiceModel_Closes_Connection_When_ObjectContent_CopyToAsync_Throws(string uri, TransferMode transferMode)
        {
            // Arrange
            server = CreateServer(transferMode);
            Task<HttpResponseMessage> task = new HttpClient().GetAsync(BaseUri(transferMode) + uri);

            // Act & Assert
            Assert.Throws<HttpRequestException>(() => task.Wait());
        }
        public void SendAsync_ServiceModel_Throws_When_StreamContent_Throws(string uri)
        {
            // Arrange
            Task task = new HttpClient(_server).GetAsync(((AzureServiceBusConfiguration)_server.Configuration).BaseAddress + uri);

            // Act & Assert
            Assert.Throws<InvalidOperationException>(() =>
                                                    {
                                                        try
                                                        {
                                                            task.Wait();
                                                        }
                                                        catch (Exception e)
                                                        {
                                                            throw e.InnerException;
                                                        }
                                                    });
        }
        public void SendAsync_ServiceModel_Closes_Connection_When_ObjectContent_CopyToAsync_Throws(string uri)
        {
            // Arrange
            Task<HttpResponseMessage> task = new HttpClient(_server).GetAsync(((AzureServiceBusConfiguration)_server.Configuration).BaseAddress + uri);

            // Act & Assert
            Assert.Throws<InvalidOperationException>(() =>
                                                    {
                                                        try
                                                        {
                                                            task.Wait();
                                                        }
                                                        catch (Exception e)
                                                        {
                                                            throw e.InnerException;
                                                        }
                                                    });
        }
예제 #13
0
파일: JokAPI.cs 프로젝트: jokio/jok-play
        public static JokUserInfo GetUser(string token, string ipaddress)
        {
            try
            {
                var url = String.Format(GetUserUrl, token, ipaddress);
                var t = new HttpClient().GetStringAsync(url);
                t.Wait();

                return JsonConvert.DeserializeObject<JokUserInfo>(t.Result);
            }
            catch
            {
                return new JokUserInfo();
            }
        }