예제 #1
0
파일: RiotApi.cs 프로젝트: Karunp/RiotSharp
        public async Task <Dictionary <string, TeamV22> > GetTeamsV22Async(Region region, List <string> teamIds)
        {
            var json = await requester.CreateRequestAsync(string.Format(TeamRootV22Url, region.ToString())
                                                          + string.Format(IdUrl, BuildNamesString(teamIds)));

            return(await JsonConvert.DeserializeObjectAsync <Dictionary <string, TeamV22> >(json));
        }
        /// <summary>
        /// Upload a new image.
        /// </summary>
        /// <param name="ImageToUploadFileData">A Byte array representing the image</param>
        /// <param name="Title">The title of the image</param>
        /// <param name="Description"> The description of the image</param>
        /// <param name="Album">The id of the album you want to add the image to. For anonymous albums, {album} should be the deletehash that is returned at creation.</param>
        /// <returns>A ImgurImage object that represents the image just uploaded</returns>
        public async Task <ImgurImage> PostImageAnonymousAsync(Byte[] ImageToUploadFileData, String Title = "", String Description = "", String Album = "")
        {
            // TODO: Make all the strings used in form content constants somewhere
            MultipartFormDataContent content = new MultipartFormDataContent(BoundaryGuid.ToString());

            content.Add(new ByteArrayContent(ImageToUploadFileData), ImgurEndpoints.ImageEndpointParameterLookup[ImageEndpointParameters.image]);
            if (Title != "")
            {
                content.Add(new StringContent(Title), ImgurEndpoints.ImageEndpointParameterLookup[ImageEndpointParameters.title]);
            }
            if (Description != "")
            {
                content.Add(new StringContent(Description), ImgurEndpoints.ImageEndpointParameterLookup[ImageEndpointParameters.description]);
            }
            if (Album != "")
            {
                content.Add(new StringContent(Album), ImgurEndpoints.ImageEndpointParameterLookup[ImageEndpointParameters.album]);
            }

            String responseString = await PostAnonymousImgurDataAsync(ImgurEndpoints.Image(), content);

            ImgurBasicWithImage returnedImage = await JsonConvert.DeserializeObjectAsync <ImgurBasicWithImage>(responseString, _defaultSerializerSettings);

            return(returnedImage.Image);
        }
예제 #3
0
        // GET: Warning
        public ActionResult Index()
        {
            int       siteId = int.Parse(System.Configuration.ConfigurationManager.AppSettings["SiteId"]);
            DataTable dt     = CRBIYYBBReportProjectRule.Intance().GetY_WarnFault(siteId);
            List <Y_WarnFaultViewModels> list = CRBICommonLib.ModelConvertHelper <Y_WarnFaultViewModels> .ConvertToModel(dt);

            foreach (var item in list)
            {
                try
                {
                    using (var httpClient = new HttpClient())
                    {
                        var url      = new Uri(System.Configuration.ConfigurationManager.AppSettings["Knowledge"]);
                        var response = httpClient.GetAsync(url + "/GetExpertKnowledge?val=" + item.EventName + "&pageNo=1&pageSize=1&strOrder=CreateTime%20DESC&equipmentCategory=-1&keyWord=").Result;
                        var data     = response.Content.ReadAsStringAsync().Result;
                        data = "{ExpertKnowledgeViewModel:" + data.Substring(0, data.LastIndexOf(']') + 1).Substring(data.IndexOf('[')) + "}";
                        data = data.Replace(@"\", "");
                        var model = JsonConvert.DeserializeObjectAsync <ExpertKnowledgesViewModel>(data).Result;
                        if (model.ExpertKnowledgeViewModel.Count > 0)
                        {
                            item.ExpertAdvice = model.ExpertKnowledgeViewModel[0].Solution ?? "";
                        }
                    }
                }
                catch
                {
                    item.ExpertAdvice = "";
                }
            }
            return(View(list));
        }
        public Task <dynamic> DownloadContent()
        {
            var responseTask = client.GetAsync(url);

            var readTask = responseTask.ContinueWith(t =>
            {
                t.Result.EnsureSuccessStatusCode();

                return(t.Result.Content.ReadAsStringAsync());
            })
                           .Unwrap();

            var deserializeTask = readTask.ContinueWith(t =>
            {
                return(JsonConvert.DeserializeObjectAsync <dynamic>(t.Result));
            })
                                  .Unwrap();

            var viewTask = deserializeTask.ContinueWith(t =>
            {
                return(this.View(t.Result));
            });

            return(viewTask);
        }
예제 #5
0
파일: VkTest.cs 프로젝트: mobydi/webrutar
        public async Task should_wallget_work()
        {
            var    ownerId     = "5029065";
            var    accessToken = "674779bd8dafe589092aee5477fe171e6e62254822a745dbd33249da52d41ac4489d2d0550ed967a00e82";
            var    offset      = 0;
            var    count       = 100;
            string reqStr      = string.Format("https://api.vkontakte.ru/method/wall.get?owner_id={0}&access_token={1}&offset={2}&count={3}&filter=owner", ownerId, accessToken, offset, count);

            var     content = await new WebClient().DownloadStringTaskAsync(reqStr);
            dynamic result  = await JsonConvert.DeserializeObjectAsync(content);


            if (result["error"] != null)
            {
                var code = result.error.error_code;
                var msg  = result.error.error_msg;
                throw new VkException(code, msg);
            }

            int pcount = result.response.First;
            IEnumerable <JToken> posts = result.response.Children();

            foreach (dynamic p in posts.Skip(1))
            {
                var id    = p.id;
                var text  = p.text;
                var likes = p.likes.count;
            }
        }
예제 #6
0
파일: vkApi.cs 프로젝트: mobydi/webrutar
        public async Task <Wall> WallGet(string ownerId, string accessToken, int offset, int count)
        {
            string reqStr = string.Format("https://api.vkontakte.ru/method/wall.get?owner_id={0}&access_token={1}&offset={2}&count={3}&filter=owner", ownerId, accessToken, offset, count);

            var content = await webClient.DownloadStringTaskAsync(reqStr);

            dynamic json = await JsonConvert.DeserializeObjectAsync(content);

            if (json["error"] != null)
            {
                var code = json.error.error_code;
                var msg  = json.error.error_msg;
                throw new VkException(code, msg);
            }

            int pcount = json.response.First;
            IEnumerable <JToken> posts = json.response.Children();

            List <Wall.Post> list = new List <Wall.Post>();

            foreach (dynamic p in posts.Skip(1))
            {
                int    id    = p.id;
                string text  = p.text;
                int    likes = p.likes.count;
                list.Add(new Wall.Post(id, text, likes));
            }
            Wall wall = new Wall(pcount, list);

            return(await Task.FromResult <Wall>(wall));
        }
예제 #7
0
        /// <summary>
        /// </summary>
        /// <param name="name"></param>
        /// <param name="region"></param>
        /// <returns>The last 10 games the summoner has played.</returns>
        public async Task <List <GameDTO> > GetSummonersRecentGamesAsync(Summoner summoner)
        {
            if (summoner == null)
            {
                throw new ArgumentNullException("summoner");
            }
            if (summoner.ID == 0)
            {
                throw new ArgumentException("Summoner ID should be a value larger than 0.");
            }

            string requestPath = string.Format("game/by-summoner/{0}/recent", summoner.ID);
            string url         = BuildURL(summoner.Region, requestPath);

            using (HttpClient client = new HttpClient())
                using (HttpResponseMessage response = await client.GetAsync(url))
                    using (HttpContent content = response.Content)
                    {
                        string contentStr = await content.ReadAsStringAsync();

                        GameHistoryDTO gameHistoryDTO = await JsonConvert.DeserializeObjectAsync <GameHistoryDTO>(contentStr);

                        if (gameHistoryDTO == null)
                        {
                            return(null);
                        }
                        return(gameHistoryDTO.games);
                    }
        }
예제 #8
0
        private string url            = "http://localhost:59880/api/Student"; // địa chỉ của api
        // GET: Home
        public ActionResult Index()
        {
            //lấy giá trị từ api xuống và lưu vào biến Result
            var res = JsonConvert.DeserializeObjectAsync <IEnumerable <Student> >(httpClient.GetStringAsync(url).Result).Result;

            return(View(res));
        }
예제 #9
0
        public async static Task <T> AccessAPI <T>(string url, RequestModelBase requestModel)
            where T : ReturnValueBase
        {
            var req = HttpWebRequest.Create(url);

            if (req == null)
            {
                throw new ArgumentException("invalid url");
            }

            req.Method               = "POST";
            req.ContentType          = "application/x-www-form-urlencoded;charset=utf-8";
            req.Headers["UserAgent"] = "snake-ddnspod/0.1.0 ([email protected])";

            using (var reqStream = await req.GetRequestStreamAsync())
            {
                var queryString = requestModel.ToQueryString();
                var bytes       = Encoding.UTF8.GetBytes(queryString);
                await reqStream.WriteAsync(bytes, 0, bytes.Length);
            }

            var res = await req.GetResponseAsync();

            using (var ResStream = res.GetResponseStream())
            {
                using (var sr = new StreamReader(ResStream))
                {
                    var data = await sr.ReadToEndAsync();

                    return(await JsonConvert.DeserializeObjectAsync <T>(data));
                }
            }
        }
예제 #10
0
        public async Task <T> LoadFileAsync <T>(string filename)
        {
            T result = default(T);

            using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
            {
                if (isf.FileExists(filename))
                {
                    try
                    {
                        using (IsolatedStorageFileStream rawStream = isf.OpenFile(filename, System.IO.FileMode.Open))
                        {
                            StreamReader reader = new StreamReader(rawStream);
                            var          json   = await reader.ReadToEndAsync();

                            result = await JsonConvert.DeserializeObjectAsync <T>(json);

                            reader.Close();
                        }
                    }
                    catch (Exception ex)
                    {
                    }
                }
            }

            return(result);
        }
예제 #11
0
        public static async Task LoadState()
        {
            var storage = ApplicationData.Current.LocalFolder;

            if ((await storage.GetFilesAsync()).All(item => item.Name != "state.json"))
            {
                AppState = new State();
                return;
            }

            var file = await storage.GetFileAsync("state.json");

            string stateContents;

            using (var fileStream = await file.OpenStreamForReadAsync())
                using (var reader = new StreamReader(fileStream, Encoding.UTF8)) {
                    stateContents = await reader.ReadToEndAsync();
                }

            try {
                AppState = await JsonConvert.DeserializeObjectAsync <State>(stateContents);

                if (AppState.ModelEdition < MODEL_EDITION)
                {
                    AppState = new State();
                }
            } catch {
                AppState = new State();
            }
        }
예제 #12
0
 public static IObservable <T> RequestAsync <T>(this HttpClient This, HttpRequestMessage request)
 {
     return(This.SendAsync(request).ToObservable()
            .ThrowOnRestResponseFailure()
            .SelectMany(x => x.Content.ReadAsStringAsync().ToObservable())
            .SelectMany(x => JsonConvert.DeserializeObjectAsync <T>(x).ToObservable()));
 }
예제 #13
0
        /// <summary>
        /// Get a champion asynchronously.
        /// </summary>
        /// <param name="region">Region from which to retrieve the data.</param>
        /// <param name="championId">Id of the champion to retrieve.</param>
        /// <param name="championData">Data to retrieve.</param>
        /// <param name="language">Language of the data to be retrieved.</param>
        /// <returns>A champion.</returns>
        public async Task <ChampionStatic> GetChampionAsync(Region region, int championId
                                                            , ChampionData championData = ChampionData.none, Language language = Language.en_US)
        {
            var wrapper = Cache.Get <ChampionStaticWrapper>(ChampionCacheKey + championId);

            if (wrapper != null && wrapper.Language == language && wrapper.ChampionData == championData)
            {
                return(wrapper.ChampionStatic);
            }
            else
            {
                var listWrapper = Cache.Get <ChampionListStaticWrapper>(ChampionsCacheKey);
                if (listWrapper != null && listWrapper.Language == language && listWrapper.ChampionData == championData)
                {
                    return(listWrapper.ChampionListStatic.Champions.Values
                           .Where((c) => c.Id == championId).FirstOrDefault());
                }
                else
                {
                    var json = await requester.CreateRequestAsync(string.Format(ChampionRootUrl, region.ToString())
                                                                  + string.Format(IdUrl, championId)
                                                                  , new List <string>() { string.Format("locale={0}", language.ToString())
                                                                                          , championData == ChampionData.none ? string.Empty
                                : string.Format("champData={0}", championData.ToString()) });

                    var champ = await JsonConvert.DeserializeObjectAsync <ChampionStatic>(json);

                    Cache.Add <ChampionStaticWrapper>(ChampionCacheKey + championId
                                                      , new ChampionStaticWrapper(champ, language, championData));
                    return(champ);
                }
            }
        }
예제 #14
0
        /// <summary>
        /// <see cref="INfieldSurveyResponseCodesService.UpdateAsync"/>
        /// </summary>
        public Task <SurveyResponseCode> UpdateAsync(string surveyId, SurveyResponseCode responseCode)
        {
            if (string.IsNullOrEmpty(surveyId))
            {
                throw new ArgumentNullException("surveyId");
            }

            if (responseCode == null)
            {
                throw new ArgumentNullException("responseCode");
            }

            var updatedresponseCode = new UpdateSurveyResponseCode
            {
                Description      = responseCode.Description,
                IsDefinite       = responseCode.IsDefinite,
                IsSelectable     = responseCode.IsSelectable,
                AllowAppointment = responseCode.AllowAppointment
            };

            return
                (Client.PatchAsJsonAsync(SurveyResponseCodeUrl(surveyId, responseCode.ResponseCode), updatedresponseCode)
                 .ContinueWith(
                     responseMessageTask =>
                     responseMessageTask.Result.Content.ReadAsStringAsync().Result)
                 .ContinueWith(
                     stringTask => JsonConvert.DeserializeObjectAsync <SurveyResponseCode>(stringTask.Result).Result)
                 .FlattenExceptions());
        }
예제 #15
0
        public async Task ProcessEventsAsync(PartitionContext context, IEnumerable <EventData> messages)
        {
            var batch = new TableBatchOperation();

            foreach (var msg in messages)
            {
                var snap = await JsonConvert.DeserializeObjectAsync <BusSnapshotInfo>(Encoding.UTF8.GetString(msg.GetBytes()));

                var entity = new DynamicTableEntity(snap.RouteShortName, snap.VehicleId.ToString());

                entity.Properties.Add("RouteShortName", EntityProperty.GeneratePropertyForString(snap.RouteShortName));
                entity.Properties.Add("VehicleId", EntityProperty.GeneratePropertyForInt(snap.VehicleId));
                entity.Properties.Add("TripId", EntityProperty.GeneratePropertyForInt(snap.TripId));
                entity.Properties.Add("Latitude", EntityProperty.GeneratePropertyForDouble(snap.Latitude));
                entity.Properties.Add("Longitude", EntityProperty.GeneratePropertyForDouble(snap.Longitude));
                entity.Properties.Add("DirectionOfTravel", EntityProperty.GeneratePropertyForString(snap.DirectionOfTravel.ToString()));
                entity.Properties.Add("NextStopId", EntityProperty.GeneratePropertyForInt(snap.NextStopId));
                entity.Properties.Add("Timeliness", EntityProperty.GeneratePropertyForString(snap.Timeliness.ToString()));
                entity.Properties.Add("TimelinessOffset", EntityProperty.GeneratePropertyForInt(snap.TimelinessOffset));
                entity.Properties.Add("Timestamp", EntityProperty.GeneratePropertyForDateTimeOffset(snap.Timestamp));

                batch.Add(TableOperation.InsertOrReplace(entity));
            }

            var tableClient = _account.CreateCloudTableClient();

            var table = tableClient.GetTableReference("snapshots");

            await table.CreateIfNotExistsAsync();

            await table.ExecuteBatchAsync(batch);

            await context.CheckpointAsync();
        }
        // GET: Home
        public ActionResult Index()
        {
            // Web API
            var model = JsonConvert.DeserializeObjectAsync <IEnumerable <Employees> >(httpClient.GetStringAsync(url).Result).Result;

            return(View(model));
        }
예제 #17
0
        /// <summary>
        /// Get languages availiable in Yandex Translator
        /// </summary>
        /// <param name="ui">//O: Terminar de</param>
        public async Task <List <string> > GetLanguagesAvailable(string ui)
        {
            List <string> returnResult = new List <string>();

            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri("https://translate.yandex.net");
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                HttpResponseMessage response = await client.GetAsync("api/v1.5/tr.json/getLangs?key=" + ApiKey + "&ui=" + ui);

                if (!response.IsSuccessStatusCode)
                {
                    throw new Exception();
                }

                var jsonString = await response.Content.ReadAsStringAsync();

                YanderResultForLang result = await JsonConvert.DeserializeObjectAsync <YanderResultForLang>(jsonString);


                foreach (var item in result.dirs)
                {
                    returnResult.Add(item);
                }
            }
            return(returnResult);
        }
        public static async Task <Project> ProjectDetails()
        {
            var request = "{0}/project/{1}/?details".FormatWith(BaseUrl, ProjectSlug);

            var client = HttpWebRequest.Create(request);

            client.Credentials     = GetCrendentials();
            client.PreAuthenticate = true;

            var wr = await client.GetResponseAsync();

            string jsonResult = string.Empty;

            using (var sr = new StreamReader(wr.GetResponseStream()))
            {
                jsonResult = await sr.ReadToEndAsync();
            }

            var model = await JsonConvert.DeserializeObjectAsync <Project>(jsonResult);

            // Always add source language
            model.Teams.Insert(0, "en");

            return(model);
        }
예제 #19
0
        public async Task <IHttpActionResult> GetSCMServiceLogs()
        {
            Services.Log.Info("Azure SCM Service Logs Requested [API]");

            var serviceName    = WebConfigurationManager.AppSettings["MS_MobileServiceName"];
            var requestBaseURI = new Uri("https://" + serviceName + ".scm.azure-mobile.net/");

            var authToken = WebConfigurationManager.AppSettings["RZ_SCMAuthToken"];

            using (var client = new HttpClient())
            {
                client.BaseAddress = requestBaseURI;
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", authToken);

                HttpResponseMessage response = await client.GetAsync("api/logs/recent");

                if (response.IsSuccessStatusCode)
                {
                    string content = await response.Content.ReadAsStringAsync();

                    List <ServiceLogSCMResponse> deserializedLogs = await JsonConvert.DeserializeObjectAsync <List <ServiceLogSCMResponse> >(content);

                    //Return Successful Responses
                    Services.Log.Info("Azure SCM Service Logs Returned [API]");
                    return(Ok(content));
                    //JUST RETURNING STRING (Not Deserialized... for NOW)
                }
                else
                {
                    Services.Log.Warn("Unable to Retreive Azure SCM Service Logs [API]");
                    return(BadRequest());
                }
            }
        }
예제 #20
0
        /// <summary>
        /// See <see cref="INfieldSurveysService.SamplingPointUpdateAsync"/>
        /// </summary>
        public Task <SamplingPoint> SamplingPointUpdateAsync(string surveyId, SamplingPoint samplingPoint)
        {
            if (samplingPoint == null)
            {
                throw new ArgumentNullException("samplingPoint");
            }

            var updatedSamplingPoint = new UpdateSamplingPoint
            {
                Name              = samplingPoint.Name,
                Description       = samplingPoint.Description,
                FieldworkOfficeId = samplingPoint.FieldworkOfficeId,
                GroupId           = samplingPoint.GroupId,
                Stratum           = samplingPoint.Stratum
            };

            string uri = string.Format(@"{0}{1}/{2}/{3}", SurveysApi.AbsoluteUri, surveyId, SamplingPointsControllerName, samplingPoint.SamplingPointId);

            return(Client.PatchAsJsonAsync(uri, updatedSamplingPoint)
                   .ContinueWith(
                       responseMessageTask => responseMessageTask.Result.Content.ReadAsStringAsync().Result)
                   .ContinueWith(
                       stringTask => JsonConvert.DeserializeObjectAsync <SamplingPoint>(stringTask.Result).Result)
                   .FlattenExceptions());
        }
예제 #21
0
        private async Task GetUser(string userId)
        {
            try
            {
                SetProgressBar("Getting user details...");

                var url = string.Format(ProfileUrl, userId, App.AuthenticationService.FourSquareAccessToken);
                Debug.WriteLine(url);
                var response = await App.HttpClient.GetAsync(url);

                if (response.StatusCode == HttpStatusCode.OK)
                {
                    var responseString = await response.Content.ReadAsStringAsync();

                    Debug.WriteLine(responseString);
                    var userResponse = await JsonConvert.DeserializeObjectAsync <FourSquareResponse <FourSquareProfileResponse> >(responseString);

                    FourSquareFriend = userResponse.Response.User;
                }
            }
            catch (Exception ex)
            {
                var s = "";
            }

            SetProgressBar();
        }
        private async void LoadHighScores(string url)
        {
            HttpClient client = new HttpClient();

            client.BaseAddress = new Uri(url);

            MessageDialog msgDlg = new MessageDialog("");

            try
            {
                var response = await client.GetAsync("");

                var responseText = await response.Content.ReadAsStringAsync();

                var users = await JsonConvert.DeserializeObjectAsync <IEnumerable <UserModel> >(responseText);

                foreach (var user in users)
                {
                    this.HighScores.Add(user);
                }
            }
            catch (Exception)
            {
                msgDlg.Content = "No connection to database. Please connect to the internet and try again.";
            }

            if (msgDlg.Content != "")
            {
                msgDlg.ShowAsync();
            }
        }
예제 #23
0
        /// <summary>
        ///     Возвращает расширенную информацию о друзьях пользователя
        /// </summary>
        /// <param name="fields">Cписок дополнительных полей, которые необходимо вернуть</param>
        /// <param name="userId">
        ///     Идентификатор пользователя, для которого необходимо получить список друзей. Если параметр не
        ///     задан, то считается, что он равен идентификатору текущего пользователя
        /// </param>
        /// <param name="order">Порядок, в котором нужно вернуть список друзей</param>
        /// <param name="listId">Идентификатор списка друзей, друзей из которого необходимо получить</param>
        /// <param name="count">Количество друзей, которое нужно вернуть</param>
        /// <param name="offset">Смещение, необходимое для выборки определенного подмножества друзей</param>
        /// <param name="nameCase">Падеж для склонения имени и фамилии пользователя</param>
        /// <param name="token">Токен для отмены выполнения запроса</param>
        /// <returns>Список друзей</returns>
        public static async Task <VKList <VKFriend> > GetExtendedAsync(
            IEnumerable <FieldsEnum> fields,
            Int64?userId            = null,
            OrderEnum?order         = null,
            Int64?listId            = null,
            Int32?count             = null,
            Int32?offset            = null,
            NameCaseEnum?nameCase   = null,
            CancellationToken?token = null
            )
        {
            VKParams param    = parseParamsForGet(fields, userId, order, listId, count, offset, nameCase);
            string   response = await VKSession.Instance.DoRequestAsync("friends.get", param);

            JObject obj = JObject.Parse(response);

            if (obj["response"] == null)
            {
                return(null);
            }
            var objArr = await JsonConvert.DeserializeObjectAsync <VKList <VKFriend> >(obj["response"].ToString());

            if (token.HasValue)
            {
                token.Value.ThrowIfCancellationRequested();
            }

            return(objArr);
        }
예제 #24
0
        /// <summary>
        /// </summary>
        /// <param name="name"></param>
        /// <param name="region"></param>
        /// <returns>The ID of a Summoner from their name and region.</returns>
        public async Task <Summoner> FromNameAsync(string name, eRegion region)
        {
            string requestPath = string.Format("summoner/by-name/{0}", name);
            string url         = BuildURL(region, requestPath);

            using (HttpClient client = new HttpClient())
                using (HttpResponseMessage response = await client.GetAsync(url))
                    using (HttpContent content = response.Content)
                    {
                        string contentStr = await content.ReadAsStringAsync();

                        var result = await JsonConvert.DeserializeObjectAsync <Dictionary <string, SummonerDTO> >(contentStr);

                        SummonerDTO summonerDTO = result.Select(x => x.Value).FirstOrDefault();

                        if (summonerDTO == null)
                        {
                            return(null);
                        }
                        //todo: cache summoners.
                        Summoner summoner = new Summoner(summonerDTO);
                        summoner.Region = region;
                        return(summoner);
                    }
        }
예제 #25
0
        /// <summary>
        /// </summary>
        /// <param name="username"></param>
        /// <param name="authToken"></param>
        /// <returns></returns>
        public static async Task <Account> Update(string username, string authToken)
        {
            long timestamp = Timestamps.GenerateRetardedTimestamp();
            var  postData  = new Dictionary <string, string>
            {
                { "username", username },
                { "timestamp", timestamp.ToString(CultureInfo.InvariantCulture) }
            };
            HttpResponseMessage response =
                await WebRequests.Post("updates", postData, authToken, timestamp.ToString(CultureInfo.InvariantCulture));

            switch (response.StatusCode)
            {
            case HttpStatusCode.OK:
            {
                // Http Request Worked
                string data = await response.Content.ReadAsStringAsync();

                Account parsedData = await JsonConvert.DeserializeObjectAsync <Account>(data);

                // we updated n shit
                return(!parsedData.Logged ? null : parsedData);
            }

            default:
                // Well, f**k
                return(null);
            }
        }
예제 #26
0
        private async Task GetUser(string userId)
        {
            var url = string.Format(UserUrl, userId, App.AuthenticationService.InstagramTokenResponse.AccessToken);

            Debug.WriteLine(url);

            SetProgressBar("Getting user details...");
            try
            {
                var response = await App.HttpClient.GetAsync(url);

                if (response.StatusCode == HttpStatusCode.OK)
                {
                    var responseString = await response.Content.ReadAsStringAsync();

                    var userResponse = await JsonConvert.DeserializeObjectAsync <InstagramUserResponse>(responseString);

                    if (userResponse != null)
                    {
                        InstagramUser = userResponse.User;
                    }
                }
            }
            catch (Exception ex)
            {
                Log.ErrorException("GetUser()", ex);
            }

            SetProgressBar();
        }
        public ActionResult Delete(int id)
        {
            var model =
                JsonConvert.DeserializeObjectAsync <Album>(httpClient.GetStringAsync(url + id).Result).Result;

            return(View(model));
        }
예제 #28
0
        private async Task GetAuthenticationToken(string code)
        {
            SetProgressBar("Talking to Instagram...");
            var para = GetAuthParams(code);

            try
            {
                var response = await App.HttpClient.PostAsync(TokenUrl, new FormUrlEncodedContent(para));

                if (response.StatusCode == HttpStatusCode.OK)
                {
                    var responseString = await response.Content.ReadAsStringAsync();

                    if (!string.IsNullOrEmpty(responseString))
                    {
                        var userResponse = await JsonConvert.DeserializeObjectAsync <InstagramTokenResponse>(responseString);

                        App.AuthenticationService.SaveInstagramUser(userResponse);

                        IsAuthenticated = true;
                    }
                }
            }
            catch (Exception ex)
            {
                Log.ErrorException("GetAuthenticationToken()", ex);
            }

            SetProgressBar();
        }
예제 #29
0
        internal async Task <Models.Settings> Read()
        {
            var files = _storage.GetFileNames(_IsolatedSettingsFile);

            if (!files.Any())
            {
                return(BuildNewConfig());
            }

            var storageFs = new IsolatedStorageFileStream(_IsolatedSettingsFile, System.IO.FileMode.Open, _storage);
            var reader    = new StreamReader(storageFs);

            var settingsJson = await reader.ReadToEndAsync();

            var settingsData = await JsonConvert.DeserializeObjectAsync <Models.Settings>(settingsJson);

            reader.Close();

            if (string.IsNullOrWhiteSpace(settingsData.ConfigVersion) || settingsData.ConfigVersion != Application.ProductVersion)
            {
                return(BuildNewConfig());
            }

            return(settingsData);
        }
예제 #30
0
파일: RiotApi.cs 프로젝트: Karunp/RiotSharp
        /// <summary>
        /// Get the teams for the specified ids asynchronously.
        /// </summary>
        /// <param name="region">Region in which the teams are located.</param>
        /// <param name="summonerIds">List of summoner ids.</param>
        /// <returns>A map of teams indexed by their id.</returns>
        public async Task <Dictionary <long, List <Team> > > GetTeamsAsync(Region region, List <int> summonerIds)
        {
            var json = await requester.CreateRequestAsync(string.Format(TeamRootUrl, region.ToString())
                                                          + string.Format(TeamBySummonerURL, BuildIdsString(summonerIds)));

            return(await JsonConvert.DeserializeObjectAsync <Dictionary <long, List <Team> > >(json));
        }