Example #1
0
        public async Task <bool> UpdateDataAsync(SlidersData item)
        {
            if (item == null || string.IsNullOrEmpty(item.Id) || !IsConnected)
            {
                return(false);
            }

            var serializedItem = _serializer.SerializeObject(item);

            var response = await _client.PutAsync(new Uri($"api/SlidersData/{item.Id}"), new StringContent(serializedItem, Encoding.UTF8, "application/json"));

            return(response.IsSuccessStatusCode);
        }
        //TODO: Use Media Type to choose serialization method
        private string Serialize(object toSerialize, string mediaType)
        {
            if (mediaType.ToLower().EndsWith("json"))
            {
                return(_jsonConverter.SerializeObject(toSerialize));
            }

            if (mediaType.ToLower().EndsWith("x-www-form-urlencoded"))
            {
                return(SerializeToFormEncodedString(_jsonConverter.SerializeObject(toSerialize)));
            }

            return(toSerialize.ToString());
        }
Example #3
0
        /// <summary>
        ///     Makes the API call.
        /// </summary>
        /// <typeparam name="TResult">The type of the result.</typeparam>
        /// <param name="url">The URL.</param>
        /// <param name="method">The method.</param>
        /// <param name="data">The data.</param>
        /// <returns></returns>
        public async Task <TResult> MakeAsyncApiCall <TResult>(string url, HttpMethod method, object data = null)
            where TResult : class
        {
            url = url.Replace("http://", "https://");

            using (var httpClient = new HttpClient())
            {
                using (var request = new HttpRequestMessage {
                    RequestUri = new Uri(url), Method = method
                })
                {
                    // add content
                    if (method != HttpMethod.Get)
                    {
                        var json = _jsonConverter.SerializeObject(data);
                        request.Content = new StringContent(json, Encoding.UTF8, "application/json");
                    }

                    var response = new HttpResponseMessage();
                    try
                    {
                        response = await httpClient.SendAsync(request).ConfigureAwait(false);
                    }
                    catch (Exception)
                    {
                        // log error
                    }

                    var stringSerialized = await response.Content.ReadAsStringAsync().ConfigureAwait(false);

                    // deserialize content
                    return(_jsonConverter.DeserializeObject <TResult>(stringSerialized));
                }
            }
        }
Example #4
0
        public virtual void SaveFragmentCacheConfigurationState(Bundle outState, IMvxJsonConverter serializer)
        {
            if (outState == null)
            {
                return;
            }

            var    mvxCachedFragmentInfosToSave           = CreateMvxCachedFragmentInfosToSave();
            string serializedMvxCachedFragmentInfosToSave = serializer.SerializeObject(mvxCachedFragmentInfosToSave);

            outState.PutString(SavedFragmentCacheConfiguration, serializedMvxCachedFragmentInfosToSave);
            outState.PutBoolean(SavedFragmentCacheConfigurationEnabledFragmentPoppedCallbackState, EnableOnFragmentPoppedCallback);
        }
Example #5
0
        public async Task RestTask()
        {
            // based on star wars example
            await Task.Delay(10);

            try
            {
                //var result = await _navigationService.Navigate<TrackAddViewModel, Track>();
                //var strTrackName = result.Name;

                var response = await _restClient.MakeApiCall <UserResponse>(_strUrl, HttpMethod.Post, _request);

                Message = "Rest : ";
                if (null != response)
                {
                    Message += _mvxJsonConverter.SerializeObject(response);
                }
            }
            catch (Exception ex)
            {
                Message = "Error " + ex.Message;
            }
        }
Example #6
0
        public async Task <TResult> MakeApiCall <TResult>(string url, HttpMethod method, object data = null, string token = null) where TResult : class
        {
            url = url.Replace("http://", "https://");

            using (var httpClient = new HttpClient())
            {
                using (var request = new HttpRequestMessage {
                    RequestUri = new Uri(url), Method = method
                })
                {
                    request.Headers.Clear();
                    var accessToken = token ?? await _storageHelper.GetAccessToken();

                    request.Headers.Authorization = new AuthenticationHeaderValue(accessToken);

                    // add content
                    if (method != HttpMethod.Get)
                    {
                        var json = _jsonConverter.SerializeObject(data);
                        request.Content = new StringContent(json, Encoding.UTF8, "application/json");
                    }

                    HttpResponseMessage response = new HttpResponseMessage();
                    try
                    {
                        response = await httpClient.SendAsync(request).ConfigureAwait(false);

                        if (response.StatusCode == System.Net.HttpStatusCode.Unauthorized)
                        {
                            throw new ApplicationException("The session was expired. Please, re-login.");
                        }
                    }
                    catch (Exception ex)
                    {
                        _mvxLog.ErrorException("MakeApiCall failed", ex);
                        throw;
                    }

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

                    return(_jsonConverter.DeserializeObject <TResult>(stringSerialized));
                }
            }
        }
        public async Task <TResult> MakeApiCall <TResult>(string requestUri, HttpMethod method, object data = null) where TResult : class
        {
            using (var httpClient = new HttpClient())
            {
                var request = new HttpRequestMessage
                {
                    RequestUri = new Uri(requestUri),
                    Method     = method,
                };

                // add content
                if (method != HttpMethod.Get)
                {
                    var json = _jsonConverter.SerializeObject(data);
                    request.Content = new StringContent(json, Encoding.UTF8, "application/json");
                }

                var response = new HttpResponseMessage();
                try
                {
                    response = await httpClient.SendAsync(request).ConfigureAwait(false);
                }
                catch (Exception ex)
                {
                    _mvxLog.ErrorException("MakeApiCall failed", ex);
                }
                response.EnsureSuccessStatusCode();

                if (response.Content != null)
                {
                    var stringSerialized = await response.Content.ReadAsStringAsync().ConfigureAwait(false);

                    // deserialize content
                    return(_jsonConverter.DeserializeObject <TResult>(stringSerialized));
                }

                return(null);
            }
        }
Example #8
0
        public async Task <TResult> MakeApiCall <TResult>(string url, HttpMethod method, object data = null, bool NeedAuth = false) where TResult : class
        {
            //url = url.Replace("http://", "https://");

            using (var request = new HttpRequestMessage {
                RequestUri = new Uri(url), Method = method
            }) {
                // add content
                if (method != HttpMethod.Get)
                {
                    var json = _jsonConverter.SerializeObject(data);
                    request.Content = new StringContent(json, Encoding.UTF8, "application/json");
                }
                HttpClient.DefaultRequestHeaders
                .Accept
                .Add(new MediaTypeWithQualityHeaderValue("application/json"));
                if (NeedAuth && TokenResponseModel != null)
                {
                    HttpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer", TokenResponseModel.Token);
                }

                HttpResponseMessage response = new HttpResponseMessage();
                try {
                    response = await HttpClient.SendAsync(request, HttpCompletionOption.ResponseContentRead).ConfigureAwait(false);
                } catch (WebException ex) {
                    IsConnected = false;
                    _mvxLog.ErrorException($"MakeApiCall failed ", ex);
                } catch (Exception e) {
                    IsConnected = e.InnerException == null || !(e.InnerException is WebException);
                    _mvxLog.ErrorException("MakeApiCall failed ", e);
                }

                var stringSerialized = await response.Content.ReadAsStringAsync().ConfigureAwait(false);

                // deserialize content
                var result = _jsonConverter.DeserializeObject <TResult>(stringSerialized);
                return(result);
            }
        }
Example #9
0
        public async Task <bool> RefreshData()
        {
            try
            {
                var data = await _client.GetData();

                foreach (var session in data.Sessions ?? new List <Session>())
                {
                    var speaker = data.Speakers.FirstOrDefault(s => s.Id == session.SpeakerId);

                    if (speaker == null)
                    {
                        continue;
                    }

                    session.SpeakerName = speaker.Name;
                }

                try
                {
                    _fileManager.WriteFile(DataFileName, _jsonConverter.SerializeObject(data));
                }
                catch (Exception)
                {
                }

                _campData = data;

                return(true);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                return(false);
            }
        }
Example #10
0
 public static string ToJson <T>(this T @object, IMvxJsonConverter jsonConverter) where T : class
 {
     return(jsonConverter.SerializeObject(@object));
 }
Example #11
0
        public async Task <ServiceResult <TResult> > MakeApiCall <TResult>(string url, HttpMethod method, object data = null, string accessToken = "") where TResult : class
        {
            var serviceResult = new ServiceResult <TResult>();

            if (CrossConnectivity.Current.IsConnected)
            {
                //url = url.Replace("http://", "https://");

                using (var httpClient = new HttpClient(new NativeMessageHandler {
                    UseCookies = false
                }))
                {
                    httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);

                    using (var request = new HttpRequestMessage {
                        RequestUri = new Uri(url), Method = method
                    })
                    {
                        // add content
                        if (method != HttpMethod.Get)
                        {
                            //if (data is ByteArrayContent)
                            //{
                            //    using (var multipartFormDataContent = new MultipartFormDataContent())
                            //    {
                            //        multipartFormDataContent.Add(data as ByteArrayContent, "file", "file.data");
                            //        request.Content = multipartFormDataContent;
                            //    }
                            //}
                            //else
                            if (data is ByteArrayContent)
                            {
                                request.Content = data as ByteArrayContent;
                            }
                            else
                            {
                                var json          = _jsonConverter.SerializeObject(data);
                                var stringContent = new StringContent(json, Encoding.UTF8, "application/json");
                                request.Content = stringContent;
                            }
                        }

                        HttpResponseMessage response = new HttpResponseMessage();
                        try
                        {
                            response = await httpClient.SendAsync(request).ConfigureAwait(false);
                        }
                        catch (Exception ex)
                        {
                            serviceResult.Success           = false;
                            serviceResult.Error.Description = ex.Message;
                            serviceResult.Error.Code        = ErrorStatusCode.Empty;
                        }

                        var stringSerialized = await response.Content.ReadAsStringAsync().ConfigureAwait(false);

                        if (response.IsSuccessStatusCode)
                        {
                            try
                            {
                                var resultObject = _jsonConverter.DeserializeObject <TResult>(stringSerialized);

                                serviceResult.Success = true;
                                serviceResult.Result  = resultObject;
                            }
                            catch (Exception ex)
                            {
                                serviceResult.Success           = false;
                                serviceResult.Error.Description = ex.Message;
                                serviceResult.Error.Code        = Enums.ErrorStatusCode.Empty;
                            }
                        }
                        else
                        {
                            serviceResult.Success           = false;
                            serviceResult.Error.Description = stringSerialized;
                            serviceResult.Error.Code        = (ErrorStatusCode)response.StatusCode;
                        }
                    }
                }
            }
            else
            {
                serviceResult.Success           = false;
                serviceResult.Error.Description = "Check internet connection.";
            }

            return(serviceResult);
        }
Example #12
0
 /// <summary>
 /// Saves the data to the file system.
 /// </summary>
 /// <param name="feedbackData">Data that should be saved</param>
 public void SaveData(FeedbackData feedbackData)
 {
     _fileStore.WriteFile(DataFileName, _jsonConverter.SerializeObject(feedbackData));
 }
Example #13
0
 public QueueEntity(IQueuedCommand command, IMvxJsonConverter jsonConverter)
 {
     this.CommandTypeName = command.GetType().FullName;
     this.SerializedObject = jsonConverter.SerializeObject(command);
 }