void OnEnteredForeground() { var since = Time.Since(_enteredBackground); EB.Debug.Log("OnEnteredForeground: since: {0}", since); EB.Debug.Log("OnEnteredForeground: reachability: {0}", Application.internetReachability); EB.Debug.Log("OnEnteredForeground: _wasLoggedIn: {0}, _wasServiceActive: {1}", _wasLoggedIn, _wasServiceActive); if (_wasLoggedIn) { var ping = ApiEndPoint.Post("/util/ping"); ping.suspendMethod = Request.eSuspendMethod.Break; ApiEndPoint.Service(ping, delegate(Response r) { if (r.sucessful) { EB.Debug.Log("OnEnteredForeground: ping is ok!"); ApiEndPoint.StartKeepAlive(); } else { EB.Debug.Log("OnEnteredForeground: sesstion timedout, re-login"); Disconnect(false); } }); for (int i = 0, cnt = _managers.Count; i < cnt; ++i) { var manager = _managers[i]; manager.OnEnteredForeground(); } } _enteredBackground = 0; }
public void Test_EmbedParameters() { // No parameters var urlFragment = "/foo/bar"; var endPoint = new ApiEndPoint(urlFragment, "GET"); Assert.AreEqual(urlFragment, endPoint.GetUrl()); endPoint.SetParameters(new[] { "ignore" }); Assert.AreEqual(urlFragment, endPoint.GetUrl()); endPoint.SetParameters(new[] { "ignore", "ignore" }); Assert.AreEqual(urlFragment, endPoint.GetUrl()); // One parameter urlFragment = "/foo/{0}/bar"; endPoint = new ApiEndPoint(urlFragment, "GET"); Assert.AreEqual(urlFragment, endPoint.GetUrl()); endPoint.SetParameters(new[] { "123" }); Assert.AreEqual("/foo/123/bar", endPoint.GetUrl()); endPoint.SetParameters(new[] { "123", "ignore" }); Assert.AreEqual("/foo/123/bar", endPoint.GetUrl()); // Two parameters urlFragment = "/foo/{0}/bar/{1}"; endPoint = new ApiEndPoint(urlFragment, "GET"); Assert.AreEqual(urlFragment, endPoint.GetUrl()); endPoint.SetParameters(new[] { "123", "456" }); Assert.AreEqual("/foo/123/bar/456", endPoint.GetUrl()); }
public ActionResult EditArticle(int id) { var url = ApiEndPoint.GenerateGetArticleByIdUrl(id); try { using (HttpClient httpClient = new HttpClient()) { ViewBag.ListCategory = GetCategory(); HttpResponseMessage runResult = httpClient.GetAsync(url).Result; if (!runResult.IsSuccessStatusCode) { //request failed TempData["AritcleDetailStatus"] = "Get article detais infor failed, Id : " + id; return(RedirectToAction("ArticleDetail", new { id = id })); } else { var jsonString = runResult.Content.ReadAsStringAsync().Result; var article = JsonConvert.DeserializeObject <Article>(jsonString); return(View(article)); } } } catch (Exception err) { Debug.WriteLine(err.Message); Debug.WriteLine("Can not connect to API"); TempData["AritcleDetailStatus"] = $"{err.Message} at index: {id}"; return(RedirectToAction("ArticeDetail", new { id = id })); } }
public ActionResult ArticleDetail(int id) { //call api var url = ApiEndPoint.GenerateGetArticleByIdUrl(id); try { using (HttpClient httpClient = new HttpClient()) { HttpResponseMessage runResult = httpClient.GetAsync(url).Result; if (!runResult.IsSuccessStatusCode) { //request failed TempData["AritcleDetailStatus"] = "Get article detais infor failed at index: " + id; return(RedirectToAction("ListPendingArticle")); } else { var jsonString = runResult.Content.ReadAsStringAsync().Result; var article = JsonConvert.DeserializeObject <Article>(jsonString); return(View(article)); } } } catch (Exception err) { Debug.WriteLine(err.Message); TempData["AritcleDetailStatus"] = $"{err.Message} at index: {id}"; return(RedirectToAction("ListPendingArticle")); } }
/// <summary> /// Initializes a new instance of the <see cref="ServiceBase{TService, TModel}"/> class. /// </summary> /// <param name="serviceAdapter">The service adapter used to interact with the MTG API.</param> /// <param name="version">The version of the API (currently only 1 version.)</param> /// <param name="endpoint">The end point of the service.</param> /// <param name="rateLimitOn">Turn the rate limit on or off.</param> public ServiceBase(IMtgApiServiceAdapter serviceAdapter, ApiVersion version, ApiEndPoint endpoint, bool rateLimitOn) { Adapter = serviceAdapter; Version = version; EndPoint = endpoint; _isRateLimitOn = rateLimitOn; }
public static async Task <T2> PostItem <T1, T2>(T1 item, ApiEndPoint enpoint, string subpath = null) { if (TokenExpiry != default && TokenExpiry < DateTimeOffset.Now) { Console.WriteLine("**** Re -logged in ****"); TokenExpiry = default; await RefreshAccessTokenWithtoken(); } var myContent = JsonConvert.SerializeObject(item); var content = new StringContent(myContent, Encoding.UTF8, "application/json"); var path = enpoint.ToString(); if (!string.IsNullOrWhiteSpace(subpath)) { path = path + @"/" + subpath; } using (var response = await WebClient.PostAsync(path, content)) { if (!response.IsSuccessStatusCode) { var result = await response.Content.ReadAsStringAsync(); throw new Exception(result); } else { var result = await response.Content.ReadAsApiResponseForType <T2>(requestBody : myContent); return(result); } } }
public static async Task <T2> PostForm <T1, T2>(T1 item, ApiEndPoint enpoint, string subpath = null) { if (TokenExpiry != default && TokenExpiry < DateTimeOffset.Now) { Console.WriteLine("**** Re -logged in ****"); TokenExpiry = default; await RefreshAccessTokenWithtoken(); } var myContent = new FormUrlEncodedContent(item.ToKeyValue()); var path = enpoint.ToString(); if (!string.IsNullOrWhiteSpace(subpath)) { path = path + @"/" + subpath; } using (var response = await WebClient.PostAsync(path, myContent)) { if (!response.IsSuccessStatusCode) { var result = await response.Content.ReadAsStringAsync(); throw new Exception(result); } else { var result = await response.Content.ReadAsObjectAsync <Models.BaseApiResponse <T2> >(); if (result.Status == Models.ResponseStatus.Error) { throw new Exception(result.ErrorMessage); } return(result.Result); } } }
public static async Task <T> PostRequest <T>(ApiEndPoint enpoint, string subpath = null) { if (TokenExpiry != default && TokenExpiry < DateTimeOffset.Now) { TokenExpiry = default; Console.WriteLine("**** Re-logged in ****"); await RefreshAccessTokenWithtoken(); } var path = enpoint.ToString(); if (!string.IsNullOrWhiteSpace(subpath)) { path = path + @"/" + subpath; } using (var response = await WebClient.PostAsync(path, null)) { if (!response.IsSuccessStatusCode) { var result = await response.Content.ReadAsStringAsync(); throw new Exception(result); } else { var result = await response.Content.ReadAsApiResponseForType <T>(requestBody : path); return(result); } } }
/// <summary> /// Initializes a new instance of the <see cref="ServiceBase{TService, TModel}"/> class. /// </summary> /// <param name="serviceAdapter">The service adapter used to interact with the MTG API.</param> /// <param name="version">The version of the API (currently only 1 version.)</param> /// <param name="endpoint">The end point of the service.</param> /// <param name="rateLimitOn">Turn the rate limit on or off.</param> public ServiceBase(IMtgApiServiceAdapter serviceAdapter, ApiVersion version, ApiEndPoint endpoint, bool rateLimitOn) { Adapter = serviceAdapter; Version = version; EndPoint = endpoint; _isRateLimitOn = rateLimitOn; WhereQueries = new Dictionary <string, string>(); }
void OnDestroy() { ApiEndPoint.Dispose(); for (int i = 0, cnt = _managers.Count; i < cnt; ++i) { var manager = _managers[i]; manager.Dispose(); } }
public static void Send(ApiEndPoint endPoint, ClientData clientData, string session) { try { Debug.WriteLine("Creating uploader thread..."); var worker = new Thread(async() => { int retryCounter = 1; retry: Conf.Log($"[{session}@{retryCounter}/{_maxRetries}] attempting to forward message to endpoint {endPoint}..."); try { var jsonMessage = JsonConvert.SerializeObject(clientData); using (var client = new WebClient()) { client.Headers.Set(HttpRequestHeader.UserAgent, $"NotificationForwarder/{Conf.GetVersion()}"); client.Headers.Set(HttpRequestHeader.ContentType, "application/json"); if (endPoint.UseHttpAuth) { Conf.Log($"[{session}@{retryCounter}/{_maxRetries}] using http basic authentication."); client.Credentials = endPoint.Credential.GetNetworkCredential(); } if (endPoint.UseProxy) { Conf.Log($"[{session}@{retryCounter}/{_maxRetries}] using proxy, type: {endPoint.Proxy.Type}."); client.Proxy = endPoint.Proxy.ToIWebProxy(); } _ = await client.UploadDataTaskAsync(endPoint.Address, "POST", Encoding.UTF8.GetBytes(jsonMessage)).ConfigureAwait(false); } Conf.Log($"[{session}@{retryCounter}/{_maxRetries}] successfully forwarded message to {endPoint}.", LogLevel.Complete); Conf.CurrentConf.LastSuccessfulForward = DateTime.Now; Conf.CurrentConf.NotificationsForwarded++; } catch (Exception ex) { Conf.Log($"[{session}@{retryCounter}/{_maxRetries}] unable to forward message to endpoint {endPoint}: {ex.Message}, HRESULT 0x{ex.HResult:x}", LogLevel.Warning); if (retryCounter < _maxRetries) { retryCounter++; goto retry; } else { Conf.Log($"[{session}@{retryCounter}/{_maxRetries}] couldn't send data: all {retryCounter} retries to {endPoint} failed.", LogLevel.Error); } } }) { IsBackground = true }; worker.Start(); } catch (Exception ex) { Conf.Log($"[{session}] uploader thread failed: {ex.Message}, HRESULT 0x{ex.HResult:x}", LogLevel.Warning); } }
/// < inheritdoc /> public Uri BuildUri(ApiEndPoint apiEndPoint, string parameterValue) { if (string.IsNullOrWhiteSpace(parameterValue)) { throw new ArgumentNullException("parameterValue"); } return(new Uri( $"{BASE_URL}/{string.Join("/", apiEndPoint.Name, parameterValue)}")); }
void SubSystemDisconnect(bool isLogout) { EB.Debug.Log("SparxHub: SubSystemDisconnect"); for (int i = _subsystems.Count - 1; i >= 0; --i) { SubSystem system = _subsystems[i]; system.Disconnect(isLogout); system.State = SubSystemState.Disconnected; } ApiEndPoint.StopKeepAlive(); }
protected void Application_Start() { AreaRegistration.RegisterAllAreas(); GlobalConfiguration.Configure(WebApiConfig.Register); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); GlobalConfiguration.Configuration.Formatters.Clear(); GlobalConfiguration.Configuration.Formatters.Add(new JsonMediaTypeFormatter()); GlobalConfiguration.Configuration.EnsureInitialized(); ApiEndPoint.Entry(this.AdditionalMapperConfig); }
public ActionResult EditArticle(int Id, ArticleDataBindingModel model) { ViewBag.ListCategory = GetCategory(); if (ModelState.IsValid) { var editArticle = ApiEndPoint.GenerateUpdateAricleUrl(Id); try { using (HttpClient httpClient = new HttpClient()) { var jsonString = JsonConvert.SerializeObject(model); var data = new StringContent(jsonString, Encoding.UTF8, "application/json"); Debug.WriteLine(data); HttpResponseMessage result = httpClient.PutAsync(editArticle, data).Result; if (!result.IsSuccessStatusCode) { TempData["Status"] = "Fail to save "; //request failed Debug.WriteLine("[failed]"); return(View(model)); } var jsonResult = result.Content.ReadAsStringAsync().Result; if (jsonResult == null) { Debug.WriteLine("[null response]"); return(View(model)); } var articleResult = JsonConvert.DeserializeObject <Article>(jsonResult); TempData["Status"] = "[Success save:]" + articleResult.Id; Debug.WriteLine("[success]"); return(RedirectToAction("ArticleDetail", new { id = articleResult.Id })); } } catch (Exception err) { TempData["Status"] = "Fail connect to api"; Debug.WriteLine(err.Message); Debug.WriteLine("[failed]"); return(View(model)); } } else { return(View(model)); } }
private static Uri ConstructUri( ApiDataSource apiDataSource, ApiEndPoint apiEndPoint, IEnumerable <string> inputParameters) { var query = apiEndPoint .Parameters .Where(w => !string.IsNullOrWhiteSpace(w)) .Zip(inputParameters, (a, b) => $"{a}={b}") .DefaultIfEmpty(string.Empty) .Aggregate((a, b) => $"{a}&{b}"); return(new Uri($"{apiDataSource.BaseURL}{apiEndPoint.UriExtension}{query}")); }
void SubSystemConnecting() { var allConnected = true; for (int i = 0, cnt = _subsystems.Count; i < cnt; ++i) { SubSystem system = _subsystems[i]; switch (system.State) { case SubSystemState.Error: { FatalError(Localizer.GetString("ID_SPARX_ERROR_UNKNOWN")); return; } case SubSystemState.Connecting: case SubSystemState.Disconnected: { allConnected = false; return; } case SubSystemState.Connected: { } break; } } if (allConnected) { EB.Debug.Log("SparxHub: SubSystemConnected"); State = HubState.Connected; ApiEndPoint.StartKeepAlive(); if (Config.LoginConfig.Listener != null) { Config.LoginConfig.Listener.OnLoggedIn(); } for (int i = 0, cnt = _managers.Count; i < cnt; ++i) { var manager = _managers[i]; EB.Debug.Log("manager.OnLoggedIn()===>{0}", manager.GetType().FullName); manager.OnLoggedIn(); } } }
protected ServiceBase( IHeaderManager headerManager, IModelMapper modelMapper, ApiVersion version, ApiEndPoint endpoint, IRateLimit rateLimit) { _headerManager = headerManager; ModelMapper = modelMapper; Version = version; EndPoint = endpoint; _rateLimit = rateLimit; ResetCurrentUrl(); }
/// < inheritdoc /> public Uri BuildUri(ApiEndPoint apiEndPoint, NameValueCollection parameters) { if (parameters == null) { throw new ArgumentNullException("parameters"); } var builder = new UriBuilder($"{BASE_URL}/{apiEndPoint.Name}"); var query = HttpUtility.ParseQueryString(builder.Query); query.Add(parameters); builder.Query = query.ToString(); return(builder.Uri); }
public ActionResult Read(int?id) { var listCategory = GetCategory(); var listArticle = GetListArticle(); if (id == null) { id = 1; } //call api var url = ApiEndPoint.GenerateGetArticleByIdUrl(id); try { using (HttpClient httpClient = new HttpClient()) { HttpResponseMessage runResult = httpClient.GetAsync(url).Result; if (!runResult.IsSuccessStatusCode) { //request failed TempData["AritcleDetailStatus"] = "Get article detais infor failed at index: " + id; return(RedirectToAction("Index")); } else { //request success var jsonString = runResult.Content.ReadAsStringAsync().Result; var article = JsonConvert.DeserializeObject <Article>(jsonString); var relatedArticle = listArticle.Where(a => a.CategoryId == article.CategoryId).Take(6).ToList(); var viewModel = new ReadArticleViewModel() { CurrentArticle = article, CurrentCategory = listCategory.Where(c => c.Id == article.CategoryId).FirstOrDefault(), RelatedArticles = relatedArticle, TopFiveLatest = listArticle.Take(5).ToList() }; return(View("Article", viewModel)); } } } catch (Exception err) { Debug.WriteLine(err.Message); TempData["AritcleDetailStatus"] = $"{err.Message} at index: {id}"; return(RedirectToAction("Index")); } }
public void List_Returns_Correct_Items() { // arrange var expected = new[] { ApiEndPoint.Search, ApiEndPoint.BoardGame, ApiEndPoint.Collection, ApiEndPoint.Thread, ApiEndPoint.GeekList }; // act var result = ApiEndPoint.List(); // assert Assert.Equal(expected, result); }
public ConfigurationReader(string configurationFileName) { if (string.IsNullOrWhiteSpace(configurationFileName)) { throw new ArgumentNullException(nameof(configurationFileName)); } string configurationRoot = Directory.GetParent( Assembly.GetExecutingAssembly().Location ).FullName; IConfiguration _configuration = new ConfigurationBuilder() .SetBasePath(configurationRoot) .AddJsonFile(configurationFileName, optional: false, reloadOnChange: true) .Build(); _apiEndPoint = _configuration.Get<ApiEndPoint>(); }
void OnEnteredBackground() { _wasLoggedIn = State == HubState.Connected; _wasServiceActive = (ApiEndPoint is HttpEndPoint) && (ApiEndPoint as HttpEndPoint).ServiceActive; EB.Debug.Log("OnEnteredBackground: _wasLoggedIn: {0}, _wasServiceActive: {1}", _wasLoggedIn, _wasServiceActive); if (_wasLoggedIn) { for (int i = _managers.Count - 1; i >= 0; --i) { Manager manager = _managers[i]; manager.OnEnteredBackground(); } ApiEndPoint.StopKeepAlive(); } _enteredBackground = Time.Now; }
public Uri BuildUri(ApiEndPoint apiEndPoint, string parameterValue, NameValueCollection parameters) { if (string.IsNullOrWhiteSpace(parameterValue)) { throw new ArgumentNullException("parameterValue"); } if (parameters == null) { throw new ArgumentNullException("parameters"); } var builder = new UriBuilder($"{BASE_URL}/{string.Join("/", apiEndPoint.Name, parameterValue)}"); var query = HttpUtility.ParseQueryString(builder.Query); query.Add(parameters); builder.Query = query.ToString(); return(builder.Uri); }
public ActionResult BrowserAnArticle(int Id, ArticleDataBindingModel article) { var updateArticleApiUrl = ApiEndPoint.GenerateUpdateAricleUrl(Id); try { using (HttpClient httpClient = new HttpClient()) { article.Status = 1; var jsonString = JsonConvert.SerializeObject(article); var data = new StringContent(jsonString, Encoding.UTF8, "application/json"); HttpResponseMessage result = httpClient.PutAsync(updateArticleApiUrl, data).Result; if (!result.IsSuccessStatusCode) { //request failed Debug.WriteLine("failed"); TempData["UpdateArticleStatus"] = "Updated failed"; return(RedirectToAction("ArticleDetail", new { id = Id })); } var jsonResult = result.Content.ReadAsStringAsync().Result; var articleResult = JsonConvert.DeserializeObject <Article>(jsonResult); TempData["UpdateArticleStatus"] = "Updated failed"; return(RedirectToAction("ListPendingArticle")); } } catch (Exception err) { TempData["UpdateArticleStatus"] = "Cannot connect to API"; Debug.WriteLine(err.Message); return(RedirectToAction("ArticleDetail", new { id = Id })); } }
public ActionResult Search(string keyword, int?page) { var apiEndPoint = ApiEndPoint.GenerateSearchByKeywordUrl(keyword); var listResult = new List <Article>(); //setting for paged list // 1. Tham số int? dùng để thể hiện null và kiểu int // page có thể có giá trị là null và kiểu int. // 2. Nếu page = null thì đặt lại là 1. if (page == null) { page = 1; } // 4. Tạo kích thước trang (pageSize) hay là số Link hiển thị trên 1 trang int pageSize = 6; // 4.1 Toán tử ?? trong C# mô tả nếu page khác null thì lấy giá trị page, còn // nếu page = null thì lấy giá trị 1 cho biến pageNumber. int pageNumber = (page ?? 1); try { using (HttpClient httpClient = new HttpClient()) { HttpResponseMessage getListResult = httpClient.GetAsync(apiEndPoint).Result; if (!getListResult.IsSuccessStatusCode) { TempData["SearchStatus"] = "Not Found"; //request failed Debug.WriteLine("No result found"); } var jsonResult = getListResult.Content.ReadAsStringAsync().Result; var listArticle = JsonConvert.DeserializeObject <List <Article> >(jsonResult); listResult = listArticle; } } catch (Exception err) { TempData["SearchStatus"] = "Can not connect to API"; Debug.WriteLine(err.Message); Debug.WriteLine("Can not connect to API"); } ViewData["Keyword"] = keyword; IPagedList <Article> pagedList = null; if (listResult == null) { var empty = new List <Article>(); pagedList = empty.ToPagedList(pageNumber, pageSize); } pagedList = listResult.ToPagedList(pageNumber, pageSize); //get list category var listCategory = GetCategory(); //get top three latest news var allArticle = GetListArticle(); var topthree = (from a in allArticle orderby a.CreatedAt select a).Take(3).ToList(); var viewModel = new SearchResultModel { ListArticle = pagedList, ListCategory = listCategory, TopThreeLatest = topthree }; return(View(viewModel)); }
/// <summary> /// Initializes a new instance of the <see cref="ServiceBase{TService, TModel}"/> class. /// </summary> /// <param name="serviceAdapter">The service adapter used to interact with the MTG API.</param> /// <param name="version">The version of the API (currently only 1 version.)</param> /// <param name="endpoint">The end point of the service.</param> public ServiceBase(IMtgApiServiceAdapter serviceAdapter, ApiVersion version, ApiEndPoint endpoint) { this._adapter = serviceAdapter; this._version = version; this._endpoint = endpoint; }