/** * Get the countries. */ public async Task <APIGatewayProxyResponse> UpdateCountry(IDataStores dataStores, IDictionary <string, string> requestHeaders, JObject requestBody) { Debug.Tested(); Debug.AssertValid(dataStores); Debug.AssertValid(requestHeaders); Debug.AssertValidOrNull(requestBody); try { // Log call LoggingHelper.LogMessage($"AdminCountryService::UpdateCountry()"); // Get the NoSQL DB client AmazonDynamoDBClient dbClient = dataStores.GetNoSQLDataStore().GetDBClient(); Debug.AssertValid(dbClient); // Check inputs Country country = CountryServiceLogicLayer.CheckValidUpdateCountryRequest(requestBody); // Check security User user = await APIHelper.CheckLoggedInAsAdmin(dbClient, requestHeaders); Debug.AssertValid(user); // Perform logic bool created = await CountryServiceLogicLayer.UpdateCountry(dbClient, loggedInUserId, country); // Return response return(new APIGatewayProxyResponse { StatusCode = created ? APIHelper.STATUS_CODE_CREATED : APIHelper.STATUS_CODE_NO_CONTENT }); } catch (Exception exception) { Debug.Unreachable(); return(APIHelper.ResponseFromException(exception)); } }
//[CommonAuthen] public JsonResult DoneResaMobile(string resacode) { try { var result = APIHelper.CallAPI <JsonResultData>("resa/doneresamobile", new { resacode = resacode, username = LoginUser.Current.USERNAME }); if (result.IsOk) { //var resainfo = new //{ // Resacode = resacode, // User = LoginUser.Current.USERNAME //}; var data = new { TYPE = "RESA", URL = string.Format("/resa/detail?id={0}", resacode), MESSAGE = string.Format("Resa {0} has done by {1}", resacode, LoginUser.Current.USERNAME), USERCREATED = LoginUser.Current.USERNAME, }; SocketHelper.Current.SendMessage("pushnotification", data); } return(Json(result, JsonRequestBehavior.AllowGet)); } catch (Exception ex) { return(Json(new JsonResultData { IsOk = false, Msg = ex.ToString() }, JsonRequestBehavior.AllowGet)); } }
public async Task <string> GetCorporationIcons(string reason, long id, int size) { var res = await APIHelper.RequestWrapper <JsonClasses.CorpIconsData>($"{SettingsManager.Settings.Config.ESIAddress}latest/corporations/{id}/icons/?datasource=tranquility&language={_language}", reason); if (res == null) { return(null); } switch (size) { case 64: return(res.px64x64); case 128: return(res.px128x128); case 256: return(res.px256x256); default: return(null); } }
/// <summary> /// 查看更多消息 /// </summary> private void GetMoreMessage() { if (ChatMessageList != null && ChatMessageList.Count > 0) { if (ChatMessageList[0].type == kWCMessageType.LocalTypeNotice && ChatMessageList[0].content.Contains("无更多聊天记录")) { return; } } long lastSendTime; string sessJid = ServiceLocator.Current.GetInstance <MainViewModel>().Sess.Jid;//显示 if (ChatMessageList.Count == 0) { lastSendTime = Helpers.DatetimeToStamp(DateTime.Now, true);//如果无消息传入当前时间 } else { lastSendTime = Helpers.DatetimeToStamp(Helpers.StampToDatetime(ChatMessageList[0].timeSend), true);//获取毫秒时间戳 } // if (HttpService == null) { //消息数量为0 或者 第一条消息不为"无更多消息"的提示消息 ,就调用历史消息 if (ChatMessageList.Count == 0 || (!ChatMessageList[0].content.Contains("无更多聊天记录") && ChatMessageList[0].type != kWCMessageType.LocalTypeNotice)) { App.Current.Dispatcher.Invoke(() => { IsLoading = true; }); HttpService = APIHelper.GetMessageAsync(sessJid, lastSendTime); HttpService.UploadDataCompleted += GetMessagesComplete; } } }
public async static Task <InputOutput> SendToParse(string input) { using (HttpResponseMessage response = await APIHelper.PostJsonAsync(APIURL.ParseSystem, new Input { text = input }, new CancellationToken())) { string rtb; InputOutput model = new InputOutput(); switch (Convert.ToInt32(response.StatusCode)) { case 200: ParsedSystem = JsonConvert.DeserializeObject <DAM.Model.System>(await response.Content.ReadAsStringAsync()); model.Output = ShowOutput(ParsedSystem); break; case 418: ParsedSystem = null; DAM.Model.DACException misstake = JsonConvert.DeserializeObject <DACException>(await response.Content.ReadAsStringAsync()); model.Output = $"Встречена ошибка в тексте! {misstake.message}"; //AccessMatrixClient.MainForm.ActiveForm model.MisstakeWord = misstake.markFrom; model.MisstakeLetter = misstake.markTo; //input = MatchWrongInput(input, response); break; case 500: default: model.Output = "Неизвестная ошибка!"; break; } //model.Input = Helper.Help.FormatInput(input); return(model); } }
public async Task <ActionResult> AuthorizeUsingClientCred() { BearerToken b = await APIHelper.GetInstance().GetTokenWithClientCredentials(); AccountProfile account = await APIHelper.GetInstance().GetAccountProfile(); if (account != null) { List <Character> chars = account.wow_accounts.First().characters.ToList(); ViewBag.Response = chars.OrderBy(x => x.realm.name).Select(x => x.name + " - " + x.realm.name).ToArray(); ViewBag.Battletag = await APIHelper.GetInstance().GetUserInfo(); ViewBag.Mounts = await APIHelper.GetInstance().GetAccountMounts(); ViewBag.Pets = await APIHelper.GetInstance().GetAccountPets(); } ViewBag.Guild = await APIHelper.GetInstance().GetGuild("silvermoon", "aerithium"); ViewBag.CharacterProfile = await APIHelper.GetInstance().GetCharacterProfile("silvermoon", "aerithium"); return(View("Authorize")); }
public async Task <Models.BankAccountResponse> CreateTransferAsync(Models.BankAccountRequest body, String customerId) { string _baseUri = Configuration.GetBaseURI(); StringBuilder _queryBuilder = new StringBuilder(_baseUri); _queryBuilder.Append("/customers/{customer-id}/bankaccounts"); APIHelper.AppendUrlWithTemplateParameters(_queryBuilder, new Dictionary <string, object>() { { "customer-id", customerId } }); string _queryUrl = APIHelper.CleanUrl(_queryBuilder); var _headers = Utilities.APIHelper.GetHeader(); var _body = APIHelper.JsonSerialize(body); HttpRequest _request = ClientInstance.PostBody(_queryUrl, _headers, _body); HttpStringResponse _response = (HttpStringResponse)await ClientInstance.ExecuteAsStringAsync(_request).ConfigureAwait(false); HttpContext _context = new HttpContext(_request, _response); base.ValidateResponse(_response, _context); try { return(APIHelper.JsonDeserialize <Models.BankAccountResponse>(_response.Body)); } catch (Exception _ex) { throw new APIException("Failed to parse the response: " + _ex.Message, _context); } }
public async Task ExecuteEnviarComentarioCommand() { //Novo comentario NovoComentario.UsuarioId = App.UsuarioLogado.Id; NovoComentario.UsuarioDados = App.UsuarioLogado; NovoComentario.Data = DateTime.Now; NovoComentario.Meu = true; try { using (APIHelper API = new APIHelper()) { await API.PUT("api/posts/comentar/" + Post.Id + "?Texto=" + NovoComentario.Texto, null); } } catch (HTTPException EX) { } catch (Exception EX) { } Comentarios.Add(NovoComentario); Post.QuantidadeComentarios++; Post.EuComentei = true; NovoComentario = new PostInteracao(); }
/// <summary> /// Categories are subdivisions within an account. /// The `defaultCategory` from [`/api/v2/accounts`](#operations-tag-Accounts) is where the main balance and transactions are held. /// Other categories are used for Savings Goals. /// </summary> /// <param name="accountUid">Required parameter: Account uid</param> /// <param name="categoryUid">Required parameter: Category uid</param> /// <param name="paymentOrderUid">Required parameter: Payment order uid</param> /// <return>Returns the void response from the API call</return> public async Task DeleteCancelStandingOrderAsync(Guid accountUid, Guid categoryUid, Guid paymentOrderUid) { //the base uri for api requests var baseUri = Configuration.GetBaseURI(); //prepare query string for API call var queryBuilder = new StringBuilder(baseUri); queryBuilder.Append("/api/v2/payments/local/account/{accountUid}/category/{categoryUid}/standing-orders/{paymentOrderUid}"); //process optional template parameters APIHelper.AppendUrlWithTemplateParameters(queryBuilder, new Dictionary <string, object> { { "accountUid", accountUid }, { "categoryUid", categoryUid }, { "paymentOrderUid", paymentOrderUid } }); //validate and preprocess url var queryUrl = APIHelper.CleanUrl(queryBuilder); //append request with appropriate headers and parameters var headers = APIHelper.GetRequestHeaders(true, true); //prepare the API call request to fetch the response var request = ClientInstance.Delete(queryUrl, headers, null); //invoke request and get response var response = (HttpStringResponse)await ClientInstance.ExecuteAsStringAsync(request).ConfigureAwait(false); var context = new HTTPContext(request, response); //handle errors ValidateResponse(response, context); }
private async Task <T> GetAgressiveESIEntry <T>(string url, string reason, object id, int retries) where T : class { if (id == null || id.ToString() == "0") { return(null); } var data = await GetFromDbCache <T>(id, 1); if (data == null) { var result = await APIHelper.AggressiveESIRequestWrapper <T>(url, reason, retries); if (!result.Data.IsFailed) { data = result.Result; if (data != null) { await UpdateDbCache(data, id, 1); } } } return(data); }
/// <summary> /// 注册的时候,检查手机号是否被注册,并发送验证短信。 /// </summary> /// <param name="phoneNum"></param> /// <returns></returns> public async static Task <CommonRespMsg> CheckPhoneNum(string phoneNum, string zone = "86") { var dic = new List <KeyValuePair <string, string> >(); dic.Add(new KeyValuePair <string, string>("appkey", UrlHelper.APP_KEY)); dic.Add(new KeyValuePair <string, string>("mobile", phoneNum)); dic.Add(new KeyValuePair <string, string>("zone", zone)); var url = UrlHelper.MakeFullUrlForGetReq(UrlHelper.CheckPhoneNumUrl, dic); try { return(await APIHelper.SendGetRequestAsync(url)); } catch (APIException e) { throw e; } catch (Exception ex) { var task = ExceptionHelper.WriteRecord(ex, nameof(CloudServices), nameof(CheckPhoneNum)); throw ex; } }
public async static Task <CommonRespMsg> GetImgeInfoAsync(string imgID, bool isLogined) { try { var dic = new List <KeyValuePair <string, string> >(); dic.Add(new KeyValuePair <string, string>("access_token", UrlHelper.ACCESS_TOKEN)); dic.Add(new KeyValuePair <string, string>("uid", UrlHelper.UID)); dic.Add(new KeyValuePair <string, string>("appkey", UrlHelper.APP_KEY)); dic.Add(new KeyValuePair <string, string>("imgid", imgID)); var url = UrlHelper.MakeFullUrlForGetReq(isLogined?UrlHelper.GetImageDetailUrl:UrlHelper.GetPublicImageDetailUrl, dic); return(await APIHelper.SendGetRequestAsync(url)); } catch (Exception e) { var task = ExceptionHelper.WriteRecord(e, nameof(CloudServices), nameof(GetImgeInfoAsync)); var resultMsg = new CommonRespMsg() { IsSuccessful = false, ErrorMsg = e.Message }; return(resultMsg); } }
protected virtual IEnumerable CreateDCLShipment(PXAdapter adapter) { List <SOOrder> list = adapter.Get <SOOrder>().ToList(); var adapterSlice = (adapter.MassProcess, adapter.QuickProcessFlow, adapter.AllowRedirect); for (int i = 0; i < list.Count; i++) { var order = list[i]; if (adapterSlice.MassProcess) { PXProcessing <SOOrder> .SetCurrentItem(order); } DCLShipmentRequestEntity model = new DCLShipmentRequestEntity(); CombineDLCShipmentEntity(model, order); PXNoteAttribute.SetNote(Base.Document.Cache, order, APIHelper.GetJsonString(model)); order.GetExtension <SOOrderExt>().UsrDCLShipmentCreated = true; #region Send Data to DCL for Create Shipment(Implement) //var dclResult = DCLHelper.CallDCLToCreateShipment(this.DCLSetup.Select().RowCast<LUMVendCntrlSetup>().FirstOrDefault(), model); //var response = APIHelper.GetObjectFromString<DCLShipmentResponseEntity>(dclResult.ContentResult); //if (dclResult.StatusCode == System.Net.HttpStatusCode.OK) // order.GetExtension<SOOrderExt>().UsrDCLShipmentCreated = true; //else // throw new PXException(response.error_message); #endregion Base.Document.Cache.Update(order); } Base.Persist(); return(adapter.Get()); }
internal static Filters GenerateFromGroupFilter(NancyContext ctx, SVR_GroupFilter gf, int uid, bool nocast, bool notag, int level, bool all, bool allpic, int pic, TagFilter.Filter tagfilter) { Filters f = new Filters { id = gf.GroupFilterID, name = gf.GroupFilterName }; var _ = new List <string>(); var gfs = RepoFactory.GroupFilter.GetByParentID(f.id).AsParallel() // Not invisible in clients .Where(a => a.InvisibleInClients == 0 && // and Has groups or is a directory ((a.GroupsIds.ContainsKey(uid) && a.GroupsIds[uid].Count > 0) || (a.FilterType & (int)GroupFilterType.Directory) == (int)GroupFilterType.Directory) && // and is not a blacklisted tag !((a.FilterType & (int)GroupFilterType.Tag) != 0 && TagFilter.IsTagBlackListed(a.GroupFilterName, tagfilter, ref _))); if (_.Count > 0) { gfs = gfs.Concat(_.Select(tag => RepoFactory.GroupFilter.GetAll().FirstOrDefault(a => { if (a.FilterType != (int)GroupFilterType.Tag) { return(false); } if (tag.Equals("Original Work")) { return(a.GroupFilterName.Equals("new")); } return(a.GroupFilterName.Equals(tag, StringComparison.InvariantCultureIgnoreCase)); })).AsParallel()); } if (level > 0) { var filters = gfs.Select(cgf => Filter.GenerateFromGroupFilter(ctx, cgf, uid, nocast, notag, level - 1, all, allpic, pic, tagfilter)).ToList(); if (gf.FilterType == ((int)GroupFilterType.Season | (int)GroupFilterType.Directory)) { f.filters = filters.OrderBy(a => a.name, new SeasonComparator()).Cast <Filters>().ToList(); } else { f.filters = filters.OrderByNatural(a => a.name).Cast <Filters>().ToList(); } f.size = filters.Count; } else { f.size = gfs.Count(); } f.url = APIHelper.ConstructFilterIdUrl(ctx, f.id); return(f); }
/// <summary> /// User Registration API /// </summary> /// <param name="Models.UserRegistrationInput">Object containing request parameters</param> /// <param name="queryParameters">Additional optional query parameters are supported by this endpoint</param> /// <return>Returns the Models.UserRegistrationModelResponse response from the API call</return> public async Task <Models.UserRegistrationModelResponse> UserRegistrationAsync(Models.UserRegistrationInput input, Dictionary <string, object> queryParameters = null) { //validating required parameters if (null == input.Email) { throw new ArgumentNullException("email", "The property \"Email\" in the input object cannot be null."); } if (null == input.User) { throw new ArgumentNullException("user", "The property \"User\" in the input object cannot be null."); } if (null == input.Password) { throw new ArgumentNullException("password", "The property \"Password\" in the input object cannot be null."); } //the base uri for api requests string _baseUri = Configuration.GetBaseURI(Configuration.Servers.PATH); //prepare query string for API call StringBuilder _queryBuilder = new StringBuilder(_baseUri); _queryBuilder.Append("/a/u/r"); //process optional query parameters APIHelper.AppendUrlWithQueryParameters(_queryBuilder, new Dictionary <string, object>() { { "email", input.Email }, { "user", input.User }, { "password", input.Password }, { "name", input.Name }, { "phone", input.Phone }, { "countrycode", input.Countrycode }, { "address", input.Address } }, ArrayDeserializationFormat, ParameterSeparator); //append optional parameters to the query APIHelper.AppendUrlWithQueryParameters(_queryBuilder, queryParameters, ArrayDeserializationFormat, ParameterSeparator); //validate and preprocess url string _queryUrl = APIHelper.CleanUrl(_queryBuilder); //append request with appropriate headers and parameters var _headers = new Dictionary <string, string>() { { "user-agent", "SMASH" } }; //prepare the API call request to fetch the response HttpRequest _request = ClientInstance.Get(_queryUrl, _headers); //Custom Authentication to be added for authorization AuthUtility.AppendCustomAuthParams(_request); //invoke request and get response HttpStringResponse _response = (HttpStringResponse)await ClientInstance.ExecuteAsStringAsync(_request).ConfigureAwait(false); HttpContext _context = new HttpContext(_request, _response); //return null on 404 if (_response.StatusCode == 404) { return(null); } //handle errors defined at the API level base.ValidateResponse(_response, _context); try { return(APIHelper.JsonDeserialize <Models.UserRegistrationModelResponse>(_response.Body)); } catch (Exception _ex) { throw new APIException("Failed to parse the response: " + _ex.Message, _context); } }
//进入该页即开始推广,自动创建用户,关联APPID protected void Page_Load(object sender, EventArgs e) { int AppID = DataConverter.CLng(Request.QueryString["appid"]); B_UserAPP appBll = new B_UserAPP(); int puid = DataConverter.CLng(Session["WX_PUserID"]); string rurl = DataConvert.CStr(Session["WX_R"]); //if (puid < 1) { function.WriteErrMsg("推荐用户不存在"); } M_WX_APPID appMod = new M_WX_APPID();//自行置入缓存,使用时取出 appMod = WxPayApi.Pay_GetByID(AppID); if (string.IsNullOrEmpty(rurl)) { string url = HttpUtility.UrlEncode(SiteConfig.SiteInfo.SiteUrl + "/User/"); rurl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + appMod.APPID + "&redirect_uri=" + url + "&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect"; } string code = Request["code"]; string access_token = APIHelper.GetWebResult("https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + appMod.APPID + "&secret=" + appMod.Secret + "&code=" + code + "&grant_type=authorization_code"); JObject obj = (JObject)JsonConvert.DeserializeObject(access_token); JObject userobj = (JObject)JsonConvert.DeserializeObject(APIHelper.GetWebResult("https://api.weixin.qq.com/sns/userinfo?access_token=" + obj["access_token"] + "&openid=" + obj["openid"] + "&lang=zh_CN")); string openID = obj["openid"].ToString(); M_UserAPP umod = appBll.SelModelByOpenID(openID, "wechat"); M_UserInfo mu = new M_UserInfo(); if (umod != null) { mu = buser.SelReturnModel(umod.UserID); buser.SetLoginState(mu); try { string vpath = SiteConfig.SiteOption.UploadDir + "User/" + mu.UserName + "/wxheadimg.jpg"; HttpHelper.DownFile(userobj["headimgurl"].ToString(), vpath); mu.UserFace = vpath; buser.UpdateByID(mu); } catch (Exception ex) { } if (puid > 0 && DataConvert.CLng(mu.ParentUserID) <= 0) { if (puid == mu.UserID) { function.WriteErrMsg("不能绑定自己!"); } else { string err = ""; if (CheckParentUser(puid, mu.UserID, ref err)) { mu.ParentUserID = puid.ToString(); buser.UpdateByID(mu); } else { function.WriteErrMsg("绑定失败,错误信息:" + err); } } } Response.Redirect(rurl); } else //新用户则注册 { umod = new M_UserAPP(); mu.UserName = "******" + DateTime.Now.ToString("yyyyMMddHHmmss") + function.GetRandomString(2).ToLower(); mu.UserPwd = StringHelper.MD5(function.GetRandomString(6)); mu.Email = function.GetRandomString(10) + "@wx.com"; mu.Question = function.GetRandomString(5); mu.Answer = function.GetRandomString(5); mu.ParentUserID = puid.ToString(); mu.TrueName = userobj["nickname"].ToString(); try { string vpath = SiteConfig.SiteOption.UploadDir + "User/" + mu.UserName + "/wxheadimg.jpg"; HttpHelper.DownFile(userobj["headimgurl"].ToString(), vpath); mu.UserFace = vpath; } catch (Exception ex) { } mu.GroupID = 1; mu.UserID = buser.Add(mu); umod.UserID = mu.UserID; umod.SourcePlat = "wechat"; umod.OpenID = openID; appBll.Insert(umod); M_Uinfo mubase = new M_Uinfo(); mubase.UserId = mu.UserID; buser.AddBase(mubase); //推广人得积分 if (puid > 0) { M_UserInfo pmu = buser.SelReturnModel(puid); if (!pmu.IsNull) { buser.ChangeVirtualMoney(pmu.UserID, new M_UserExpHis() { score = 20, ScoreType = (int)M_UserExpHis.SType.Point, detail = "新用户[" + mu.UserName + "]注册,获得推广积分:" + 20 }); } } buser.SetLoginState(mu); Response.Redirect(rurl); } }
/// <summary> /// Creates an account under a given customer /// </summary> /// <param name="Models.CreateAccountInput">Object containing request parameters</param> /// <return>Returns the Models.AccountModel response from the API call</return> public async Task <Models.AccountModel> CreateAccountAsync(Models.CreateAccountInput input) { //validating required parameters if (null == input.CustomerIdentifier) { throw new ArgumentNullException("customerIdentifier", "The property \"CustomerIdentifier\" in the input object cannot be null."); } if (null == input.Body) { throw new ArgumentNullException("body", "The property \"Body\" in the input object cannot be null."); } //the base uri for api requests string _baseUri = Configuration.GetBaseURI(); //prepare query string for API call StringBuilder _queryBuilder = new StringBuilder(_baseUri); _queryBuilder.Append("/customers/{customerIdentifier}/accounts"); //process optional template parameters APIHelper.AppendUrlWithTemplateParameters(_queryBuilder, new Dictionary <string, object>() { { "customerIdentifier", input.CustomerIdentifier } }); //validate and preprocess url string _queryUrl = APIHelper.CleanUrl(_queryBuilder); //append request with appropriate headers and parameters var _headers = new Dictionary <string, string>() { { "user-agent", "V2NGSDK" }, { "accept", "application/json" }, { "content-type", "application/json; charset=utf-8" } }; //append body params var _body = APIHelper.JsonSerialize(input.Body); //prepare the API call request to fetch the response HttpRequest _request = ClientInstance.PostBody(_queryUrl, _headers, _body, Configuration.PlatformName, Configuration.PlatformKey); //invoke request and get response HttpStringResponse _response = (HttpStringResponse)await ClientInstance.ExecuteAsStringAsync(_request).ConfigureAwait(false); HttpContext _context = new HttpContext(_request, _response); //Error handling using HTTP status codes if ((_response.StatusCode < 200) || (_response.StatusCode > 208)) //[200,208] = HTTP OK { throw new RaasGenericException(@"API Error", _context); } //handle errors defined at the API level base.ValidateResponse(_response, _context); try { return(APIHelper.JsonDeserialize <Models.AccountModel>(_response.Body)); } catch (Exception _ex) { throw new APIException("Failed to parse the response: " + _ex.Message, _context); } }
public LogComparisonController(APIHelper apiHelper) { _apiHelper = apiHelper ?? throw new ArgumentNullException(nameof(apiHelper)); }
public async Task <ZkillEntityStats> GetKillsLossesStats(long id, bool isAlliance, DateTime?from = null, DateTime?to = null, int lastSeconds = 0) { try { var txt = isAlliance ? "allianceID" : "corporationID"; int maxPerPage = 200; var page = 1; var killsList = new List <JsonZKill.ZkillOnly>(); var query = $"https://zkillboard.com/api/kills/{txt}/{id}/npc/0/page/{{0}}"; var sysList = new List <long>(); if (lastSeconds > 0) { query += $"/pastSeconds/{lastSeconds}/"; } else if (from.HasValue) { from = from.Value.Subtract(TimeSpan.FromMinutes(from.Value.Minute)); query += $"/startTime/{from.Value:yyyyMMddHHmm}/"; to = to ?? DateTime.UtcNow; to = to.Value.Subtract(TimeSpan.FromMinutes(to.Value.Minute)); query += $"endTime/{to.Value:yyyyMMddHHmm}/"; } if (query.Last() != '/') { query += "/"; } while (true) { var res = await APIHelper.RequestWrapper <List <JsonZKill.ZkillOnly> >(string.Format(query, page), _reason); if (res != null) { killsList.AddRange(res); } if (res == null || res.Count == 0 || res.Count < maxPerPage) { break; } page++; } var lossList = new List <JsonZKill.ZkillOnly>(); query = $"https://zkillboard.com/api/losses/{txt}/{id}/npc/0/page/{{0}}"; if (lastSeconds > 0) { query += $"/pastSeconds/{lastSeconds}/"; } else if (from.HasValue) { from = from.Value.Subtract(TimeSpan.FromMinutes(from.Value.Minute)); query += $"/startTime/{from.Value:yyyyMMddHHmm}/"; to = to ?? DateTime.UtcNow; to = to.Value.Subtract(TimeSpan.FromMinutes(to.Value.Minute)); query += $"endTime/{to.Value:yyyyMMddHHmm}/"; } if (query.Last() != '/') { query += "/"; } page = 1; while (true) { var res = await APIHelper.RequestWrapper <List <JsonZKill.ZkillOnly> >(string.Format(query, page), _reason); if (res != null) { lossList.AddRange(res); } if (res == null || res.Count == 0 || res.Count < maxPerPage) { break; } page++; } var idList = killsList.Select(a => a.zkb.locationID).ToList(); idList.AddRange(lossList.Select(a => a.zkb.locationID)); var most = idList.Count > 0 ? idList.GroupBy(i => i).OrderByDescending(grp => grp.Count()) .Select(grp => grp.Key).First() : 0; var system = most > 0 ? await APIHelper.ESIAPI.GetSystemData(LogCat.Stats.ToString(), most) : null; var pl = await APIHelper.ESIAPI.GetPlanet("", most); var name = system?.name ?? pl?.name; if (!string.IsNullOrEmpty(name)) { if (name.StartsWith("Stargate")) { name = name.Replace("Stargate", "").Replace("(", "").Replace(")", "").Trim(); } else { name = name.Split(' ').FirstOrDefault(); } } var r = new ZkillEntityStats { IskDestroyed = (long)killsList.Sum(a => a.zkb.totalValue), PointsDestroyed = killsList.Sum(a => a.zkb.points), IskLost = (long)lossList.Sum(a => a.zkb.totalValue), PointsLost = lossList.Sum(a => a.zkb.points), ShipsDestroyed = killsList.Count, ShipsLost = lossList.Count, SoloKills = killsList.Count(a => a.zkb.solo), MostSystems = name }; return(r); } catch (Exception ex) { await LogHelper.LogEx(nameof(GetKillsLossesStats), ex, LogCat.Stats); return(new ZkillEntityStats()); } }
internal async Task <List <JsonZKill.ZkillOnly> > GetZKillOnlyFeed(bool isAlliance, int id) { var eText = isAlliance ? "allianceID" : "corporationID"; return(await APIHelper.RequestWrapper <List <JsonZKill.ZkillOnly> >($"https://zkillboard.com/api/{eText}/{id}/zkbOnly/orderDirection/desc/pastSeconds/3600/", _reason)); }
internal async Task <JsonZKill.CharacterStats> GetCharacterStats(object characterId) { return(await APIHelper.RequestWrapper <JsonZKill.CharacterStats>($"https://zkillboard.com/api/stats/characterID/{characterId}/", _reason)); }
public MainWindow() { InitializeComponent(); apiHelper = new APIHelper(); }
/// <summary> /// Create and submit an email message to one or more email addresses. /// </summary> /// <param name="to">Required parameter: A valid address that will receive the email. Multiple addresses can be separated by using commas.</param> /// <param name="type">Required parameter: Specifies the type of email to be sent</param> /// <param name="subject">Required parameter: The subject of the mail. Must be a valid string.</param> /// <param name="message">Required parameter: The email message that is to be sent in the text.</param> /// <param name="mfrom">Optional parameter: A valid address that will send the email.</param> /// <param name="cc">Optional parameter: Carbon copy. A valid address that will receive the email. Multiple addresses can be separated by using commas.</param> /// <param name="bcc">Optional parameter: Blind carbon copy. A valid address that will receive the email. Multiple addresses can be separated by using commas.</param> /// <param name="attachment">Optional parameter: A file that is attached to the email. Must be less than 7 MB in size.</param> /// <return>Returns the string response from the API call</return> public async Task <string> CreateSendEmailAsync( string to, Models.TypeEnum type, string subject, string message, string mfrom = null, string cc = null, string bcc = null, string attachment = null) { //the base uri for api requests string _baseUri = Configuration.BaseUri; //prepare query string for API call StringBuilder _queryBuilder = new StringBuilder(_baseUri); _queryBuilder.Append("/email/sendemails.json"); //validate and preprocess url string _queryUrl = APIHelper.CleanUrl(_queryBuilder); //append request with appropriate headers and parameters var _headers = new Dictionary <string, string>() { { "user-agent", "APIMATIC 2.0" } }; //append form/field parameters var _fields = new List <KeyValuePair <string, Object> >() { new KeyValuePair <string, object>("To", to), new KeyValuePair <string, object>("Type", Models.TypeEnumHelper.ToValue(type)), new KeyValuePair <string, object>("Subject", subject), new KeyValuePair <string, object>("Message", message), new KeyValuePair <string, object>("From", mfrom), new KeyValuePair <string, object>("Cc", cc), new KeyValuePair <string, object>("Bcc", bcc), new KeyValuePair <string, object>("Attachment", attachment) }; //remove null parameters _fields = _fields.Where(kvp => kvp.Value != null).ToList(); //prepare the API call request to fetch the response HttpRequest _request = ClientInstance.Post(_queryUrl, _headers, _fields, Configuration.BasicAuthUserName, Configuration.BasicAuthPassword); //invoke request and get response HttpStringResponse _response = (HttpStringResponse)await ClientInstance.ExecuteAsStringAsync(_request).ConfigureAwait(false); HttpContext _context = new HttpContext(_request, _response); //handle errors defined at the API level base.ValidateResponse(_response, _context); try { return(_response.Body); } catch (Exception _ex) { throw new APIException("Failed to parse the response: " + _ex.Message, _context); } }
/// <summary> /// TODO: type endpoint description here /// </summary> /// <param name="callback">Required parameter: The callback function that the JSON response will be wrapped in if desired</param> /// <param name="color">Required parameter: Vehicle color (i.e. black, white, blue, ..etc)</param> /// <param name="compressorType">Required parameter: The name of the aspiration of the vehicle engine (Acceptable values are: "", "supercharger", "twin-turbocharger", "turbocharger")</param> /// <param name="cylinders">Required parameter: The number of cylinders the vehicle engine has</param> /// <param name="drivenWheels">Required parameter: Vehicle drive type name (Acceptable values are: "", "all-wheel-drive", "front-wheel-drive", "rear-wheel-drive", "four-wheel-drive")</param> /// <param name="fuelType">Required parameter: Name of the type of fuel the vehicle engine uses (Acceptable values are: "", "electric", "natural-gas-cng", "gas", "flex-fuel-ffv", "diesel", "hybrid")</param> /// <param name="makeNiceName">Required parameter: Vehicle Make niceName</param> /// <param name="model">Required parameter: Vehicle Model name</param> /// <param name="msrp">Required parameter: Vehicle MSRP</param> /// <param name="trim">Required parameter: Vehicle trim name</param> /// <param name="vehicleStyle">Required parameter: Vehicle Style name</param> /// <param name="year">Required parameter: Vehicle model four-digit year</param> /// <param name="zip">Required parameter: Five-digit zipcode</param> /// <return>Returns the dynamic response from the API call</return> public async Task <dynamic> GetPriceAsync( string callback, string color, string compressorType, string cylinders, string drivenWheels, string fuelType, string makeNiceName, string model, string msrp, string trim, string vehicleStyle, string year, string zip) { //the base uri for api requestss string _baseUri = Configuration.BaseUri; //prepare query string for API call StringBuilder _queryBuilder = new StringBuilder(_baseUri); _queryBuilder.Append("/api/v1/vehicle/{makeNiceName}/{year}/price"); //process optional template parameters APIHelper.AppendUrlWithTemplateParameters(_queryBuilder, new Dictionary <string, object>() { { "makeNiceName", makeNiceName }, { "year", year } }); //process optional query parameters APIHelper.AppendUrlWithQueryParameters(_queryBuilder, new Dictionary <string, object>() { { "callback", callback }, { "color", color }, { "compressorType", compressorType }, { "cylinders", cylinders }, { "drivenWheels", drivenWheels }, { "fuelType", fuelType }, { "model", model }, { "msrp", msrp }, { "trim", trim }, { "vehicleStyle", vehicleStyle }, { "zip", zip }, { "api_key", Configuration.ApiKey } }); //validate and preprocess url string _queryUrl = APIHelper.CleanUrl(_queryBuilder); //append request with appropriate headers and parameters var _headers = new Dictionary <string, string>() { { "user-agent", "APIMATIC 2.0" }, { "accept", "application/json" } }; //prepare the API call request to fetch the response HttpRequest _request = ClientInstance.Get(_queryUrl, _headers); //invoke request and get response HttpStringResponse _response = (HttpStringResponse)await ClientInstance.ExecuteAsStringAsync(_request); HttpContext _context = new HttpContext(_request, _response); //handle errors defined at the API level base.ValidateResponse(_response, _context); try { return(APIHelper.JsonDeserialize <dynamic>(_response.Body)); } catch (Exception ex) { throw new APIException("Failed to parse the response: " + ex.Message, _context); } }
private static void Main(string[] args) { Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture; Thread.CurrentThread.CurrentUICulture = CultureInfo.InvariantCulture; // var ssss = new List<JsonZKill.ZkillOnly>().Count(a => a.killmail_id == 0); if (!File.Exists(SettingsManager.FileSettingsPath)) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("Please make sure you have settings.json file in bot folder! Create it and fill with correct settings."); try { Console.ReadKey(); } catch { // ignored } return; } //load settings var result = SettingsManager.Prepare(); if (!string.IsNullOrEmpty(result)) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine(result); try { Console.ReadKey(); } catch { // ignored } return; } APIHelper.Prepare(); LogHelper.LogInfo($"ThunderED v{VERSION} is running!").GetAwaiter().GetResult(); //load database provider var rs = SQLHelper.LoadProvider(); if (!string.IsNullOrEmpty(rs)) { Console.BackgroundColor = ConsoleColor.Red; Console.WriteLine(result); try { Console.ReadKey(); } catch { // ignored } return; } //update config settings if (SettingsManager.Settings.Config.ModuleNotificationFeed) { var dateStr = SQLHelper.GetCacheDataNextNotificationCheck().GetAwaiter().GetResult(); if (DateTime.TryParseExact(dateStr, new [] { "dd.MM.yyyy HH:mm:ss", $"{CultureInfo.InvariantCulture.DateTimeFormat.ShortDatePattern} {CultureInfo.InvariantCulture.DateTimeFormat.LongTimePattern}" }, CultureInfo.InvariantCulture.DateTimeFormat, DateTimeStyles.None, out var x)) { SettingsManager.NextNotificationCheck = x; } } //load language LM.Load().GetAwaiter().GetResult(); //load injected settings SettingsManager.UpdateInjectedSettings().GetAwaiter().GetResult(); //load APIs APIHelper.StartDiscord().GetAwaiter().GetResult(); while (!APIHelper.DiscordAPI.IsAvailable) { Task.Delay(10).GetAwaiter().GetResult(); } if (APIHelper.DiscordAPI.GetGuild() == null) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("[CRITICAL] DiscordGuildId - Discord guild not found!"); try { Console.ReadKey(); } catch { // ignored } return; } //Load modules TickManager.LoadModules(); //initiate core timer _timer = new Timer(TickManager.Tick, new AutoResetEvent(true), 100, 100); Console.CancelKeyPress += (sender, e) => { e.Cancel = false; _timer?.Dispose(); APIHelper.DiscordAPI.Stop(); }; while (true) { if (!SettingsManager.Settings.Config.RunAsServiceCompatibility) { var command = Console.ReadLine(); var arr = command?.Split(" "); if ((arr?.Length ?? 0) == 0) { continue; } switch (arr[0]) { case "quit": Console.WriteLine("Quitting..."); _timer.Dispose(); APIHelper.DiscordAPI.Stop(); return; case "flushn": Console.WriteLine("Flushing all notifications DB list"); SQLHelper.RunCommand("delete from notificationsList").GetAwaiter().GetResult(); break; case "flushcache": Console.WriteLine("Flushing all cache from DB"); SQLHelper.RunCommand("delete from cache").GetAwaiter().GetResult(); break; case "help": Console.WriteLine("List of available commands:"); Console.WriteLine(" quit - quit app"); Console.WriteLine(" flushn - flush all notification IDs from database"); Console.WriteLine(" getnurl - display notification auth url"); Console.WriteLine(" flushcache - flush all cache from database"); Console.WriteLine(" token [ID] - refresh and display EVE character token from database"); break; case "token": if (arr.Length == 1) { continue; } if (!long.TryParse(arr[1], out var id)) { continue; } var rToken = SQLHelper.GetRefreshTokenDefault(id).GetAwaiter().GetResult(); Console.WriteLine(APIHelper.ESIAPI .RefreshToken(rToken, SettingsManager.Settings.WebServerModule.CcpAppClientId, SettingsManager.Settings.WebServerModule.CcpAppSecret).GetAwaiter() .GetResult()); break; } Thread.Sleep(10); } else { Thread.Sleep(500); } } }
public BankTrade() { apiHelper = new APIHelper(); }
/// <summary> /// TODO: type endpoint description here /// </summary> /// <param name="callback">Required parameter: The callback function that the JSON response will be wrapped in if desired</param> /// <param name="colorid">Required parameter: Vehicle color ID (&colorid=xxx&colorid=xxx&colorid=xxx for multiples)</param> /// <param name="condition">Required parameter: Vehicle condition (Acceptable values are: "Outstanding", "Clean", "Average", "Rough", "Damaged")</param> /// <param name="fmt">Required parameter: Response format (json only) (Acceptable values are: "json")</param> /// <param name="mileage">Required parameter: Vehicle milage (e.g. 24000)</param> /// <param name="optionid">Required parameter: Vehicle option ID (&optionid=xxx&optionid=xxx&optionid=xxx for multiples)</param> /// <param name="styleid">Required parameter: Vehicle style ID</param> /// <param name="zip">Required parameter: Five-digit zipcode</param> /// <return>Returns the dynamic response from the API call</return> public async Task <dynamic> GetCalculateusedtmvAsync( string callback, string colorid, string condition, string fmt, string mileage, string optionid, string styleid, string zip) { //the base uri for api requestss string _baseUri = Configuration.BaseUri; //prepare query string for API call StringBuilder _queryBuilder = new StringBuilder(_baseUri); _queryBuilder.Append("/v1/api/tmv/tmvservice/calculateusedtmv"); //process optional query parameters APIHelper.AppendUrlWithQueryParameters(_queryBuilder, new Dictionary <string, object>() { { "callback", callback }, { "colorid", colorid }, { "condition", condition }, { "fmt", fmt }, { "mileage", mileage }, { "optionid", optionid }, { "styleid", styleid }, { "zip", zip }, { "api_key", Configuration.ApiKey } }); //validate and preprocess url string _queryUrl = APIHelper.CleanUrl(_queryBuilder); //append request with appropriate headers and parameters var _headers = new Dictionary <string, string>() { { "user-agent", "APIMATIC 2.0" }, { "accept", "application/json" } }; //prepare the API call request to fetch the response HttpRequest _request = ClientInstance.Get(_queryUrl, _headers); //invoke request and get response HttpStringResponse _response = (HttpStringResponse)await ClientInstance.ExecuteAsStringAsync(_request); HttpContext _context = new HttpContext(_request, _response); //handle errors defined at the API level base.ValidateResponse(_response, _context); try { return(APIHelper.JsonDeserialize <dynamic>(_response.Body)); } catch (Exception ex) { throw new APIException("Failed to parse the response: " + ex.Message, _context); } }
public HarborTrade() { apiHelper = new APIHelper(); }
/// <summary> /// Lists all charges /// </summary> /// <param name="page">Optional parameter: Page number</param> /// <param name="size">Optional parameter: Page size</param> /// <param name="code">Optional parameter: Filter for charge's code</param> /// <param name="status">Optional parameter: Filter for charge's status</param> /// <param name="paymentMethod">Optional parameter: Filter for charge's payment method</param> /// <param name="customerId">Optional parameter: Filter for charge's customer id</param> /// <param name="orderId">Optional parameter: Filter for charge's order id</param> /// <param name="createdSince">Optional parameter: Filter for the beginning of the range for charge's creation</param> /// <param name="createdUntil">Optional parameter: Filter for the end of the range for charge's creation</param> /// <return>Returns the Models.ListChargesResponse response from the API call</return> public async Task <Models.ListChargesResponse> GetChargesAsync( int?page = null, int?size = null, string code = null, string status = null, string paymentMethod = null, string customerId = null, string orderId = null, DateTime?createdSince = null, DateTime?createdUntil = null) { //the base uri for api requests string _baseUri = Configuration.BaseUri; //prepare query string for API call StringBuilder _queryBuilder = new StringBuilder(_baseUri); _queryBuilder.Append("/charges"); //process optional query parameters APIHelper.AppendUrlWithQueryParameters(_queryBuilder, new Dictionary <string, object>() { { "page", page }, { "size", size }, { "code", code }, { "status", status }, { "payment_method", paymentMethod }, { "customer_id", customerId }, { "order_id", orderId }, { "created_since", (createdSince.HasValue) ? createdSince.Value.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss.FFFFFFFK") : null }, { "created_until", (createdUntil.HasValue) ? createdUntil.Value.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss.FFFFFFFK") : null } }, ArrayDeserializationFormat, ParameterSeparator); //validate and preprocess url string _queryUrl = APIHelper.CleanUrl(_queryBuilder); //append request with appropriate headers and parameters var _headers = new Dictionary <string, string>() { { "user-agent", "MundiSDK - DotNet 0.16.21" }, { "accept", "application/json" } }; //prepare the API call request to fetch the response HttpRequest _request = ClientInstance.Get(_queryUrl, _headers, Configuration.BasicAuthUserName, Configuration.BasicAuthPassword); //invoke request and get response HttpStringResponse _response = (HttpStringResponse)await ClientInstance.ExecuteAsStringAsync(_request).ConfigureAwait(false); HttpContext _context = new HttpContext(_request, _response); //handle errors defined at the API level base.ValidateResponse(_response, _context); try { return(APIHelper.JsonDeserialize <Models.ListChargesResponse>(_response.Body)); } catch (Exception _ex) { throw new APIException("Failed to parse the response: " + _ex.Message, _context); } }
// GET: ProductInput public ActionResult ProductData(int flowChartMaster_Uid, string product_Date, string time_Interval) { List <OrganiztionVM> userinfo = CurrentUser.GetUserInfo.OrgInfo; int iswx = 0; if (CurrentUser.GetUserInfo.MH_Flag) { string url = string.Format("FlowChart/QueryPlantByUser?userid={0}", CurrentUser.AccountUId); HttpResponseMessage responseMessage2 = APIHelper.APIGetAsync(url); var result1 = responseMessage2.Content.ReadAsStringAsync().Result; var entity1 = JsonConvert.DeserializeObject <List <string> >(result1); foreach (string item in entity1) { if (item == "WUXI_M") { iswx = 1; } } } else { foreach (OrganiztionVM item in userinfo) { if (item.Plant == "WUXI_M") { iswx = 1; } } } ViewBag.IsWX = iswx; ProcessDataSearch search = new ProcessDataSearch(); string apiUrl = string.Format("FlowChart/QueryFlowChartDataByMasterUid?flowChartMaster_uid={0}", flowChartMaster_Uid); HttpResponseMessage responseMessage = APIHelper.APIGetAsync(apiUrl); var result = responseMessage.Content.ReadAsStringAsync().Result; var entity = JsonConvert.DeserializeObject <ProcessDataSearch>(result); //检查flowchartDetail是否有Repair和Rework---------------start apiUrl = string.Format("FlowChart/GetMaxDetailInfoAPI?flowChartMaster_uid={0}", flowChartMaster_Uid); responseMessage = APIHelper.APIGetAsync(apiUrl); result = responseMessage.Content.ReadAsStringAsync().Result; var detailList = JsonConvert.DeserializeObject <List <FlowChartDetailDTO> >(result); var hasReworkExist = detailList.Exists(m => m.Rework_Flag == "Rework"); var hasRepairExist = detailList.Exists(m => m.Rework_Flag == "Repair"); if (hasRepairExist && hasRepairExist) { ViewBag.ReworkFlag = true; } else { ViewBag.ReworkFlag = false; } //检查flowchartDetail是否有Repair和Rework---------------end //根据专案UID获取对应的OP var apiUrl1 = string.Format("EventReportManager/GetOPByFlowchartMasterUIDAPI?masterUID={0}", flowChartMaster_Uid); var responseMessage1 = APIHelper.APIGetAsync(apiUrl1); var OP = JsonConvert.DeserializeObject <string>(responseMessage1.Content.ReadAsStringAsync().Result); ViewBag.OP = OP; apiUrl = string.Format("EventReportManager/GetIntervalInfoAPI?opType={0}", OP); responseMessage = APIHelper.APIGetAsync(apiUrl); result = responseMessage.Content.ReadAsStringAsync().Result; var time = JsonConvert.DeserializeObject <IntervalEnum>(result); search.Date = DateTime.Parse(product_Date.IsNullOrWhiteSpace() ? time.NowDate : product_Date); search.Time = time_Interval.IsNullOrWhiteSpace() ? time.Time_Interval : time_Interval; search.Customer = entity.Customer; search.Project = entity.Project; search.Part_Types = entity.Part_Types; search.Product_Phase = entity.Product_Phase; search.QuertFlag = "ProjectList"; search.Func_Plant = entity.Func_Plant; search.FlowChart_Master_UID = entity.FlowChart_Master_UID; search.FlowChart_Version = entity.FlowChart_Version; TempData["ProcessDataSearch"] = search; ViewBag.Product_Date = time.NowDate; ViewBag.Time_Interval = time.Time_Interval; return(View()); }
public static Serie GenerateFromAnimeSeries(NancyContext ctx, SVR_AnimeSeries ser, int uid, bool nocast, bool notag, int level, bool all, bool allpics, int pic) { Serie sr = new Serie(); Video nv = ser.GetPlexContract(uid); List <SVR_AnimeEpisode> ael = ser.GetAnimeEpisodes(); sr.id = ser.AnimeSeriesID; sr.summary = nv.Summary; sr.year = nv.Year; sr.air = nv.AirDate.ToString("dd-MM-yyyy"); GenerateSizes(sr, ael, uid); sr.rating = nv.Rating; sr.userrating = nv.UserRating; sr.titles = nv.Titles; sr.name = nv.Title; sr.season = nv.Season; if (nv.IsMovie) { sr.ismovie = 1; } #region Images Random rand = new Random(); Contract_ImageDetails art; if (nv.Fanarts != null && nv.Fanarts.Count > 0) { if (allpics || pic > 1) { if (allpics) { pic = 999; } int pic_index = 0; foreach (Contract_ImageDetails cont_image in nv.Fanarts) { if (pic_index < pic) { sr.art.fanart.Add(new Art() { url = APIHelper.ConstructImageLinkFromTypeAndId(ctx, cont_image.ImageType, cont_image.ImageID), index = pic_index }); pic_index++; } else { break; } } } else { art = nv.Fanarts[rand.Next(nv.Fanarts.Count)]; sr.art.fanart.Add(new Art() { url = APIHelper.ConstructImageLinkFromTypeAndId(ctx, art.ImageType, art.ImageID), index = 0 }); } } if (nv.Banners != null && nv.Banners.Count > 0) { if (allpics || pic > 1) { if (allpics) { pic = 999; } int pic_index = 0; foreach (Contract_ImageDetails cont_image in nv.Banners) { if (pic_index < pic) { sr.art.banner.Add(new Art() { url = APIHelper.ConstructImageLinkFromTypeAndId(ctx, cont_image.ImageType, cont_image.ImageID), index = pic_index }); pic_index++; } else { break; } } } else { art = nv.Banners[rand.Next(nv.Banners.Count)]; sr.art.banner.Add(new Art() { url = APIHelper.ConstructImageLinkFromTypeAndId(ctx, art.ImageType, art.ImageID), index = 0 }); } } if (!string.IsNullOrEmpty(nv.Thumb)) { sr.art.thumb.Add(new Art() { url = APIHelper.ConstructImageLinkFromRest(ctx, nv.Thumb), index = 0 }); } #endregion if (!nocast) { if (nv.Roles != null) { foreach (RoleTag rtg in nv.Roles) { Role new_role = new Role(); if (!String.IsNullOrEmpty(rtg.Value)) { new_role.name = rtg.Value; } else { new_role.name = ""; } if (!String.IsNullOrEmpty(rtg.TagPicture)) { new_role.namepic = APIHelper.ConstructImageLinkFromRest(ctx, rtg.TagPicture); } else { new_role.namepic = ""; } if (!String.IsNullOrEmpty(rtg.Role)) { new_role.role = rtg.Role; } else { rtg.Role = ""; } if (!String.IsNullOrEmpty(rtg.RoleDescription)) { new_role.roledesc = rtg.RoleDescription; } else { new_role.roledesc = ""; } if (!String.IsNullOrEmpty(rtg.RolePicture)) { new_role.rolepic = APIHelper.ConstructImageLinkFromRest(ctx, rtg.RolePicture); } else { new_role.rolepic = ""; } sr.roles.Add(new_role); } } } if (!notag) { if (nv.Genres != null) { foreach (Shoko.Models.PlexAndKodi.Tag otg in nv.Genres) { Tag new_tag = new Tag { tag = otg.Value }; sr.tags.Add(new_tag); } } } if (level > 0) { if (ael.Count > 0) { sr.eps = new List <Episode>(); foreach (SVR_AnimeEpisode ae in ael) { if (!all && (ae?.GetVideoLocals()?.Count ?? 0) == 0) { continue; } Episode new_ep = Episode.GenerateFromAnimeEpisode(ctx, ae, uid, (level - 1)); if (new_ep != null) { sr.eps.Add(new_ep); } if (level - 1 > 0) { foreach (RawFile file in new_ep.files) { sr.filesize += file.size; } } } sr.eps = sr.eps.OrderBy(a => a.epnumber).ToList(); } } return(sr); }
/// <summary> /// Number Verification /// </summary> /// <param name="CreateVerifyNumberInput">Object containing request parameters</param> /// <return>Returns the string response from the API call</return> public async Task <string> CreateVerifyNumberAsync(CreateVerifyNumberInput input) { //validating required parameters if (null == input.Phonenumber) { throw new ArgumentNullException("phonenumber", "The property \"Phonenumber\" in the input object cannot be null."); } if (null == input.Type) { throw new ArgumentNullException("type", "The property \"Type\" in the input object cannot be null."); } //the base uri for api requestss string _baseUri = Configuration.GetBaseURI(); //prepare query string for API call StringBuilder _queryBuilder = new StringBuilder(_baseUri); _queryBuilder.Append("/verifycallerid/verifynumber.{ResponseType}"); //process optional template parameters APIHelper.AppendUrlWithTemplateParameters(_queryBuilder, new Dictionary <string, object>() { { "ResponseType", input.ResponseType } }); //validate and preprocess url string _queryUrl = APIHelper.CleanUrl(_queryBuilder); //append request with appropriate headers and parameters var _headers = new Dictionary <string, string>() { { "user-agent", "message360-api" } }; //append form/field parameters var _fields = new Dictionary <string, object>() { { "phonenumber", input.Phonenumber }, { "type", input.Type } }; //prepare the API call request to fetch the response HttpRequest _request = ClientInstance.Post(_queryUrl, _headers, _fields, Configuration.BasicAuthUserName, Configuration.BasicAuthPassword); //invoke request and get response HttpStringResponse _response = (HttpStringResponse)await ClientInstance.ExecuteAsStringAsync(_request).ConfigureAwait(false); HttpContext _context = new HttpContext(_request, _response); //handle errors defined at the API level base.ValidateResponse(_response, _context); try { return(_response.Body); } catch (Exception _ex) { throw new APIException("Failed to parse the response: " + _ex.Message, _context); } }