public void TestSignupNonExistantUser() { ApiHelper apiHelper = new ApiHelper(); string password = "******"; string user = string.Format(_rootEmail, Guid.NewGuid().ToString("N")); Assert.IsTrue(apiHelper.RegisterNewUser(_apiUrl, user, password)); }
public DataCollectWorker(string StorageQueueConnectionString, string TaskQueueName, string ResultQueueName, string ContainerName) : base(StorageQueueConnectionString, TaskQueueName, ContainerName) { resultQueueName = ResultQueueName; apiHelper = new ApiHelper(); }
public void TestSignupAsAUserThatAlreadyExistsButIsntValidated() { ApiHelper apiHelper = new ApiHelper(); string password = "******"; string user = string.Format(_rootEmail, "unvalidated-personal"); apiHelper.RegisterNewUser(_apiUrl, user, password); }
public ActionResult GetFormJson(string keyValue) { BannerEntity bannerEntity = bannerApp.GetEntityBySid(keyValue); return(Content(ApiHelper.JsonSerial(bannerEntity))); }
private PagedListViewModel <SyncLogItemViewModel> GetLogItem(ApiCall call, bool initem) { var sitedb = call.WebSite.SiteDb(); int pagesize = ApiHelper.GetPageSize(call); int pagenr = ApiHelper.GetPageNr(call); PagedListViewModel <SyncLogItemViewModel> model = new PagedListViewModel <SyncLogItemViewModel>(); model.PageNr = pagenr; model.PageSize = pagesize; List <SyncLogItemViewModel> result = new List <SyncLogItemViewModel>(); Guid settingid = call.GetGuidValue("SyncSettingId"); var items = sitedb.Synchronization.Query.Where(o => o.SyncSettingId == settingid && o.In == initem).SelectAll().OrderByDescending(o => o.LastModifyTick); model.TotalCount = items.Count(); model.TotalPages = ApiHelper.GetPageCount(model.TotalCount, model.PageSize); foreach (var item in items.Skip(model.PageNr * model.PageSize - model.PageSize).Take(model.PageSize)) { var repo = sitedb.GetRepository(item.StoreName); if (repo != null) { var log = sitedb.Log.Get(item.Version); if (log != null) { var siteobject = repo.GetByLog(log); SyncLogItemViewModel logitem = new SyncLogItemViewModel(); var info = ObjectService.GetObjectInfo(sitedb, siteobject as ISiteObject); logitem.Name = info.Name; logitem.Size = Lib.Utilities.CalculateUtility.GetSizeString(info.Size); logitem.ObjectType = repo.StoreName; logitem.LastModified = log.UpdateTime; logitem.LogId = log.Id; if (log.EditType == IndexedDB.EditType.Add) { logitem.ChangeType = ChangeType.Add; } else if (log.EditType == IndexedDB.EditType.Update) { logitem.ChangeType = ChangeType.Update; } else { logitem.ChangeType = ChangeType.Delete; } result.Add(logitem); } } } model.List = result; return(model); }
public List <Album> GetUserAlbums(int userid) { return(ApiHelper <Album> .GetList("https://jsonplaceholder.typicode.com/albums?userId=" + userid)); }
private async void Add_Clicked(object sender, EventArgs e) { if (string.IsNullOrWhiteSpace(viewModel.GoiVayModel.Name)) { await Shell.Current.DisplayAlert("", Language.vui_long_nhap_ten_goi_vay, Language.dong); return; } if (viewModel.MaxTimeOption == null) { await Shell.Current.DisplayAlert("", Language.vui_long_chon_thoi_han_vay_toi_da, Language.dong); return; } if (!EntryLaiSuat.Price.HasValue || EntryLaiSuat.Price.Value == 0) { await Shell.Current.DisplayAlert("", Language.vui_long_nhap_lai_suat, Language.dong); return; } if (!EntryMaxPrice.Price.HasValue || EntryMaxPrice.Price.Value == 0) { await Shell.Current.DisplayAlert("", Language.vui_long_chon_thoi_han_vay_toi_da, Language.dong); return; } if (string.IsNullOrWhiteSpace(viewModel.GoiVayModel.Condition)) { await Shell.Current.DisplayAlert("", Language.vui_long_nhap_dieu_kien_vay, Language.dong); return; } // co chon hinh khac. if (imageFile != null) { string fileName = Guid.NewGuid() + ".jpg"; StreamContent content = new StreamContent(imageFile.GetStream()); content.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data") { Name = "file", FileName = fileName }; MultipartFormDataContent form = new MultipartFormDataContent(); form.Add(content); var uploadImageResopnse = await UploadImage(form); if (uploadImageResopnse.IsSuccess) { viewModel.GoiVayModel.Image = fileName; } } GoiVay goivay = new GoiVay(); goivay.BankId = viewModel.BankId; goivay.Name = viewModel.GoiVayModel.Name; goivay.MaxTime = viewModel.MaxTimeOption.Id; goivay.MaxTimeUnit = viewModel.MaxTimeUnitOption.Id; goivay.MaxPrice = EntryMaxPrice.Price.Value; goivay.LaiSuat = EntryLaiSuat.Price.Value; goivay.Condition = viewModel.GoiVayModel.Condition; goivay.Description = viewModel.GoiVayModel.Description; goivay.Image = viewModel.GoiVayModel.Image; ApiResponse response = null; loadingPopup.IsVisible = true; if (viewModel.GoiVayModel.Id == Guid.Empty) { response = await ApiHelper.Post(ApiRouter.BANK_GOIVAY, goivay, true); } else { goivay.Id = viewModel.GoiVayModel.Id; response = await ApiHelper.Put(ApiRouter.BANK_GOIVAY, goivay, true); } if (response.IsSuccess) { this.OnSaved?.Invoke(this, EventArgs.Empty); loadingPopup.IsVisible = false; MessagingCenter.Send <AddLoanView>(this, "OnSave"); ToastMessageHelper.ShortMessage(Language.luu_thanh_cong); } else { await Shell.Current.DisplayAlert("", response.Message, Language.dong); loadingPopup.IsVisible = false; } loadingPopup.IsVisible = false; }
public JsonResult GetByPromotionId(int id) { List <PromotionApply> result = ApiHelper <List <PromotionApply> > .HttpGetAsync($"{Helper.ApiUrl}api/promotionapply/getbypromotionid/{id}"); return(Json(new { result })); }
private async Task <HttpResponseMessage> HttpResponseMessage( HttpRequest request, CancellationToken cancellationToken) { var queryBuilder = new StringBuilder(request.QueryUrl); if (request.QueryParameters != null) { ApiHelper.AppendUrlWithQueryParameters(queryBuilder, request.QueryParameters, this.arrayDeserializationFormat, parameterSeparator); } // validate and preprocess url. string queryUrl = ApiHelper.CleanUrl(queryBuilder); HttpRequestMessage requestMessage = new HttpRequestMessage { RequestUri = new Uri(queryUrl), Method = request.HttpMethod, }; if (request.Headers != null) { foreach (var headers in request.Headers) { requestMessage.Headers.TryAddWithoutValidation(headers.Key, headers.Value); } } if (!string.IsNullOrEmpty(request.Username)) { var byteArray = Encoding.UTF8.GetBytes(request.Username + ":" + request.Password); requestMessage.Headers.Authorization = new AuthenticationHeaderValue( "Basic", Convert.ToBase64String(byteArray)); } if (request.HttpMethod.Equals(HttpMethod.Delete) || request.HttpMethod.Equals(HttpMethod.Post) || request.HttpMethod.Equals(HttpMethod.Put) || request.HttpMethod.Equals(new HttpMethod("PATCH"))) { bool multipartRequest = request.FormParameters != null && (request.FormParameters.Any(f => f.Value is MultipartContent) || request.FormParameters.Any(f => f.Value is FileStreamInfo)); if (request.Body != null) { if (request.Body is FileStreamInfo file) { file.FileStream.Position = 0; requestMessage.Content = new StreamContent(file.FileStream); if (!string.IsNullOrWhiteSpace(file.ContentType)) { requestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(file.ContentType); } else if (request.Headers.Any(h => h.Key.Equals("content-type", StringComparison.OrdinalIgnoreCase))) { requestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue( request.Headers.First(h => h.Key.Equals("content-type", StringComparison.OrdinalIgnoreCase)).Value); } else { requestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); } } else if (request.Headers.ContainsKey("content-type") && string.Equals( request.Headers["content-type"], "application/json; charset=utf-8", StringComparison.OrdinalIgnoreCase)) { requestMessage.Content = new StringContent((string)request.Body ?? string.Empty, Encoding.UTF8, "application/json"); } else if (request.Headers.ContainsKey("content-type")) { byte[] bytes = null; if (request.Body is Stream) { Stream s = (Stream)request.Body; s.Position = 0; using (BinaryReader br = new BinaryReader(s)) { bytes = br.ReadBytes((int)s.Length); } } else if (request.Body is byte[]) { bytes = (byte[])request.Body; } else { bytes = Encoding.UTF8.GetBytes((string)request.Body); } requestMessage.Content = new ByteArrayContent(bytes ?? Array.Empty <byte>()); try { requestMessage.Content.Headers.ContentType = MediaTypeHeaderValue.Parse(request.Headers["content-type"]); } catch (Exception) { requestMessage.Content.Headers.TryAddWithoutValidation("content-type", request.Headers["content-type"]); } } else { requestMessage.Content = new StringContent(request.Body.ToString() ?? string.Empty, Encoding.UTF8, "text/plain"); } } else if (multipartRequest) { MultipartFormDataContent formContent = new MultipartFormDataContent(); foreach (var param in request.FormParameters) { if (param.Value is FileStreamInfo fileParam) { var fileContent = new MultipartFileContent(fileParam); fileContent.Rewind(); formContent.Add(fileContent.ToHttpContent(param.Key)); } else if (param.Value is MultipartContent wrapperObject) { wrapperObject.Rewind(); formContent.Add(wrapperObject.ToHttpContent(param.Key)); } else { formContent.Add(new StringContent(param.Value.ToString()), param.Key); } } requestMessage.Content = formContent; } else if (request.FormParameters != null) { var parameters = new List <KeyValuePair <string, string> >(); foreach (var param in request.FormParameters) { parameters.Add(new KeyValuePair <string, string>(param.Key, param.Value.ToString())); } requestMessage.Content = new FormUrlEncodedContent(parameters); } } return(await this.client.SendAsync(requestMessage, cancellationToken).ConfigureAwait(false)); }
public JsonResult Gets() { var bookings = ApiHelper <List <BookingView> > .HttpGetAsync("Booking/gets"); return(Json(new { data = bookings })); }
public MainWindow() { ApiHelper.InitializeClient(); InitializeComponent(); }
public DropDownListDataService(IConfiguration configuration) { _apiHelper = new ApiHelper(configuration["ApiClient:ApiUrl"]); }
public JsonResult DeleteByRoomTypeId(int id) { ActionsResult result = ApiHelper <ActionsResult> .HttpGetAsync($"{Helper.ApiUrl}api/facilityapply/deletebyroomtypeid/{id}", "DELETE"); return(Json(new { result })); }
public JsonResult Get(int id) { List <FacilityApply> result = ApiHelper <List <FacilityApply> > .HttpGetAsync($"{Helper.ApiUrl}api/facilityapply/getbyroomtypeid/{id}"); return(Json(new { result })); }
/// <summary> /// Provides the summary details for a single cash drawer shift. See /// RetrieveCashDrawerShiftEvents for a list of cash drawer shift events. /// </summary> /// <param name="locationId">Required parameter: The ID of the location to retrieve cash drawer shifts from.</param> /// <param name="shiftId">Required parameter: The shift ID.</param> /// <return>Returns the Models.RetrieveCashDrawerShiftResponse response from the API call</return> public async Task <Models.RetrieveCashDrawerShiftResponse> RetrieveCashDrawerShiftAsync(string locationId, string shiftId, CancellationToken cancellationToken = default) { //the base uri for api requests string _baseUri = config.GetBaseUri(); //prepare query string for API call StringBuilder _queryBuilder = new StringBuilder(_baseUri); _queryBuilder.Append("/v2/cash-drawers/shifts/{shift_id}"); //process optional template parameters ApiHelper.AppendUrlWithTemplateParameters(_queryBuilder, new Dictionary <string, object>() { { "shift_id", shiftId } }); //process optional query parameters ApiHelper.AppendUrlWithQueryParameters(_queryBuilder, new Dictionary <string, object>() { { "location_id", locationId } }, 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", userAgent }, { "accept", "application/json" }, { "Square-Version", "2020-06-25" } }; //prepare the API call request to fetch the response HttpRequest _request = GetClientInstance().Get(_queryUrl, _headers); if (HttpCallBack != null) { HttpCallBack.OnBeforeHttpRequestEventHandler(GetClientInstance(), _request); } _request = await authManagers["default"].ApplyAsync(_request).ConfigureAwait(false); //invoke request and get response HttpStringResponse _response = await GetClientInstance().ExecuteAsStringAsync(_request, cancellationToken).ConfigureAwait(false); HttpContext _context = new HttpContext(_request, _response); if (HttpCallBack != null) { HttpCallBack.OnAfterHttpResponseEventHandler(GetClientInstance(), _response); } //handle errors defined at the API level base.ValidateResponse(_response, _context); var _responseModel = ApiHelper.JsonDeserialize <Models.RetrieveCashDrawerShiftResponse>(_response.Body); _responseModel.Context = _context; return(_responseModel); }
public void SendAutoreply(MailBoxData account, MailMessage message, string httpContextScheme, ILog log) { try { if (message.Folder != FolderType.Inbox || account.MailAutoreply == null || !account.MailAutoreply.TurnOn) { return; } var utcNow = DateTime.UtcNow.Date; if (account.MailAutoreply.TurnOnToDate && account.MailAutoreply.ToDate != DateTime.MinValue && account.MailAutoreply.ToDate < utcNow) { log.InfoFormat("DisableAutoreply(MailboxId = {0}) -> time is over", account.MailBoxId); EnableAutoreply(account, false); return; } if (account.MailAutoreply.FromDate > utcNow) { log.Info("Skip MailAutoreply: FromDate > utcNow"); return; } if (account.MailAutoreply.FromDate > message.Date) { log.Info("Skip MailAutoreply: FromDate > message.Date"); return; } if (MailUtil.IsMessageAutoGenerated(message)) { log.Info("Skip MailAutoreply: found some auto-generated header"); return; } if (IsCurrentMailboxInFrom(account, message)) { log.Info("Skip MailAutoreply: message from current account"); return; } var apiHelper = new ApiHelper(httpContextScheme); var autoreplyEmail = GetAutoreplyEmailInTo(account, message); if (string.IsNullOrEmpty(autoreplyEmail)) { log.Info("Skip MailAutoreply: autoreplyEmail not found"); return; } if (HasGroupsInTo(account, message)) { log.Info("Skip MailAutoreply: has group address in TO, CC"); return; } if (HasMailboxAutoreplyHistory(account, message.FromEmail)) { log.Info("Skip MailAutoreply: already sent to this address (history)"); return; } if (account.MailAutoreply.OnlyContacts && !apiHelper.SearchEmails(message.FromEmail).Any()) { log.Info("Skip MailAutoreply: message From address is not a part of user's contacts"); return; } apiHelper.SendMessage(CreateAutoreply(account, message, autoreplyEmail), true); account.MailAutoreplyHistory.Add(message.FromEmail); log.InfoFormat("AutoreplyEngine->SendAutoreply: auto-reply message has been sent to '{0}' email", autoreplyEmail); } catch (Exception ex) { log.ErrorFormat( "AutoreplyEngine->SendAutoreply Error: {0}, innerException: {1}, account.MailBoxId = {2}, " + "account.UserId = {3}, account.TenantId = {4}", ex, ex.InnerException != null ? ex.InnerException.ToString() : string.Empty, account.MailBoxId, account.UserId, account.TenantId); } }
/// <summary> /// Lists all events for a specific subscription.. /// In the current implementation, only `START_SUBSCRIPTION` and `STOP_SUBSCRIPTION` (when the subscription was canceled) events are returned.. /// </summary> /// <param name="subscriptionId">Required parameter: The ID of the subscription to retrieve the events for..</param> /// <param name="cursor">Optional parameter: A pagination cursor returned by a previous call to this endpoint. Provide this to retrieve the next set of results for the original query. For more information, see [Pagination](https://developer.squareup.com/docs/working-with-apis/pagination)..</param> /// <param name="limit">Optional parameter: The upper limit on the number of subscription events to return in the response. Default: `200`.</param> /// <param name="cancellationToken"> cancellationToken. </param> /// <returns>Returns the Models.ListSubscriptionEventsResponse response from the API call.</returns> public async Task <Models.ListSubscriptionEventsResponse> ListSubscriptionEventsAsync( string subscriptionId, string cursor = null, int?limit = null, CancellationToken cancellationToken = default) { // the base uri for api requests. string baseUri = this.Config.GetBaseUri(); // prepare query string for API call. StringBuilder queryBuilder = new StringBuilder(baseUri); queryBuilder.Append("/v2/subscriptions/{subscription_id}/events"); // process optional template parameters. ApiHelper.AppendUrlWithTemplateParameters(queryBuilder, new Dictionary <string, object>() { { "subscription_id", subscriptionId }, }); // prepare specfied query parameters. var queryParams = new Dictionary <string, object>() { { "cursor", cursor }, { "limit", limit }, }; // append request with appropriate headers and parameters var headers = new Dictionary <string, string>() { { "user-agent", this.UserAgent }, { "accept", "application/json" }, { "Square-Version", this.Config.SquareVersion }, }; // prepare the API call request to fetch the response. HttpRequest httpRequest = this.GetClientInstance().Get(queryBuilder.ToString(), headers, queryParameters: queryParams); if (this.HttpCallBack != null) { this.HttpCallBack.OnBeforeHttpRequestEventHandler(this.GetClientInstance(), httpRequest); } httpRequest = await this.AuthManagers["global"].ApplyAsync(httpRequest).ConfigureAwait(false); // invoke request and get response. HttpStringResponse response = await this.GetClientInstance().ExecuteAsStringAsync(httpRequest, cancellationToken).ConfigureAwait(false); HttpContext context = new HttpContext(httpRequest, response); if (this.HttpCallBack != null) { this.HttpCallBack.OnAfterHttpResponseEventHandler(this.GetClientInstance(), response); } // handle errors defined at the API level. this.ValidateResponse(response, context); var responseModel = ApiHelper.JsonDeserialize <Models.ListSubscriptionEventsResponse>(response.Body); responseModel.Context = context; return(responseModel); }
public JsonResult Delete(int id) { var result = ApiHelper <ResResult> .HttpPostAsync($"booking/changestatusbooking/{id}/3", "POST", new object()); return(Json(new { data = result })); }
public void ConstructorTest() { ApiHelper helper = new ApiHelper(account, token, api); Assert.NotNull(helper); }
public JsonResult GetStatus() { var status = ApiHelper <List <StatusView> > .HttpGetAsync($"Status/statusView/{(int)Common.Table.Booking}"); return(Json(new { data = status })); }
public JsonResult DeleteByPromotionId(int id) { ActionsResult result = ApiHelper <ActionsResult> .HttpGetAsync($"{Helper.ApiUrl}api/promotionapply/deletebypromotionid/{id}", "DELETE"); return(Json(new { result })); }
public FaultInjectionResponseModel <ConfigModel> CreateBlob(ConfigModel model) { if (model == null) { throw new HttpRequestWithStatusException("Empty model", new HttpResponseException(HttpStatusCode.BadRequest)); } if (string.IsNullOrWhiteSpace(model.ClientId) || string.IsNullOrWhiteSpace(model.ClientSecret) || string.IsNullOrWhiteSpace(model.TenantId) || string.IsNullOrWhiteSpace(model.Subscription)) { throw new HttpRequestWithStatusException("ClientId/ClientSecret/TenantId/Subscription is empty", new HttpResponseException(HttpStatusCode.BadRequest)); } if (2 * model.RollbackFrequency > model.SchedulerFrequency) { throw new Exception("Power Cycle Schedule Frequency should be less than half the Scheduler Frequency, Please decrease the Power Cycle Schedule or increase the Scheduler Frequency value"); } if (2 * model.RollbackFrequency <= model.SchedulerFrequency && model.SchedulerFrequency > (model.CrawlerFrequency + model.MeanTime)) { throw new HttpRequestWithStatusException("Scheduler Frequency should be less than the sum of Crawler Frequency & Mean Time between FI on VM, Please reduce the value of Scheduler Frequency", new HttpResponseException(HttpStatusCode.BadRequest)); } try { var storageAccountName = ConfigurationManager.AppSettings[StorageAccountName]; var resourceGroupName = ConfigurationManager.AppSettings[ResourceGroupName]; if (string.IsNullOrWhiteSpace(storageAccountName) || string.IsNullOrWhiteSpace(resourceGroupName)) { throw new ArgumentNullException("Storage account name or resource group name is null " + "Storage Param: " + StorageAccountName + " Resource Param: " + ResourceGroupName); } var azure = AzureClient.GetAzure(model.ClientId, model.ClientSecret, model.TenantId, model.Subscription); var resourceGroup = azure.ResourceGroups.GetByName(resourceGroupName); if (resourceGroup == null) { throw new ArgumentNullException(ResourceGroupName, "Resource group information is empty: " + ResourceGroupName); } var storageAccounts = azure.StorageAccounts.ListByResourceGroup(resourceGroupName); IStorageAccount storageAccountInfo = null; if (storageAccounts != null && storageAccounts.Count() > 0) { storageAccountInfo = storageAccounts.FirstOrDefault(x => x.Name.Equals(storageAccountName, StringComparison.OrdinalIgnoreCase)); } if (storageAccountInfo == null) { throw new ArgumentNullException(StorageAccountName, "Storage account information is empty: " + storageAccountName); } var storageKeys = storageAccountInfo.GetKeys(); string storageConnection = string.Format(StorageConStringFormat, storageAccountName, storageKeys[0].Value); InsertOrUpdateAppsettings(StorageConnectionString, storageConnection); var storageAccount = CloudStorageAccount.Parse(storageConnection); var blockBlob = ApiHelper.CreateBlobContainer(storageAccount); var configString = ApiHelper.ConvertConfigObjectToString(model); using (var ms = new MemoryStream()) { LoadStreamWithJson(ms, configString); blockBlob.UploadFromStream(ms); } var functionAppName = CommonName + GetUniqueHash(model.ClientId + model.TenantId + model.Subscription); // TODO: ask ? do we deploy the azure functions, whenever user do any changes in the config? if (!DeployAzureFunctions(model, functionAppName, storageConnection, resourceGroupName)) { throw new HttpRequestWithStatusException("Azure Functions are not deployed", new HttpResponseException(HttpStatusCode.InternalServerError)); } // add the tenant id and application id into the configuration file to validate the user next time. InsertOrUpdateAppsettings(TenantIdString, model.TenantId); InsertOrUpdateAppsettings(ApplicationIdString, model.ClientId); return(new FaultInjectionResponseModel <ConfigModel>() { Success = true, SuccessMessage = "Deployment Completed Successfully", Result = model }); } catch (Exception e) { Console.WriteLine(e); throw; } }
public Album GetAlbum(int id) { return(ApiHelper <Album> .Get("https://jsonplaceholder.typicode.com/albums?id=" + id)); }
public async void ExecuteReportSchedule(string type = "") { string url = $"https://{apiUrl}/api/Report/Execute/{type}"; var apiHelper = new ApiHelper(_accessor).InitializeClient(); await apiHelper.GetAsync(url); }
public List <Album> GetAlbums() { return(ApiHelper <Album> .GetList("https://jsonplaceholder.typicode.com/albums")); }
public async Task FetchSim() { var result = await ApiHelper.Get <Sim>("api/sim/" + SimId); if (result.IsSuccess) { var sim = (Sim)result.Content; Title = sim.DisplayNumber; var model = new SimDetailModel(); model.Id = sim.Id; model.SimNumber = sim.SimNumber; model.DisplayNumber = sim.DisplayNumber; model.Price = sim.Price; if (FixedPrice != null) { model.Price = (decimal)FixedPrice; } model.Carrier = viewModel.CarrierOptions.SingleOrDefault(x => x.Id == sim.CarrierId); model.OwnerId = sim.OwnerId; model.Owner = sim.Owner; model.CreatedOn = sim.CreatedOn; model.Status = sim.Status.Value; model.StatusFormat = sim.StatusFormat; model.Description = sim.Description; // ko co ida chi thi an stack layout dia chi di. if (string.IsNullOrEmpty(model.Owner.Address)) { address.IsVisible = false; } else { address.IsVisible = true; } viewModel.Sim = model; if (sim.SubcribeTypeId.HasValue) { viewModel.Sim.SubcribeType = viewModel.SubcribeTypeOptions.SingleOrDefault(x => x.Id == sim.SubcribeTypeId.Value); } // ngay sinh, than tai. List <string> NumberTypeStringList = new List <string>(); await viewModel.LoadNumberTypes(); foreach (var item in viewModel.NumberTypeOptions) { if (sim.Sim_NumberTypes.Any(x => x.NumberTypeId == item.Id)) { NumberTypeStringList.Add(item.Name); } } viewModel.NumberTypesFormat = string.Join(", ", NumberTypeStringList.ToArray()); // co loai sim thi lay id cua loai sim de lay background. if (sim.Sim_NumberTypes.Count > 0) { short numberTypeId = sim.Sim_NumberTypes.FirstOrDefault().NumberTypeId; string imageName = Constants.SimDetailBackgroundDictionary.keys[numberTypeId]; if (imageName == "") { SimImage.Source = "sim1.jpg"; } else { SimImage.Source = AppConfig.API_IP + "HinhLoaiSim/" + imageName; } } if (!string.IsNullOrEmpty(sim.Owner.PictureUrl)) { img_avatar.Source = AvatarHelper.ToAvatarUrl(sim.Owner.PictureUrl); } } }
/// <summary> /// Retrieves a list of payments taken by the account making the request. /// Max results per page: 100 /// </summary> /// <param name="beginTime">Optional parameter: Timestamp for the beginning of the reporting period, in RFC 3339 format. Inclusive. Default: The current time minus one year.</param> /// <param name="endTime">Optional parameter: Timestamp for the end of the requested reporting period, in RFC 3339 format. Default: The current time.</param> /// <param name="sortOrder">Optional parameter: The order in which results are listed. - `ASC` - oldest to newest - `DESC` - newest to oldest (default).</param> /// <param name="cursor">Optional parameter: A pagination cursor returned by a previous call to this endpoint. Provide this to retrieve the next set of results for the original query. See [Pagination](https://developer.squareup.com/docs/basics/api101/pagination) for more information.</param> /// <param name="locationId">Optional parameter: Limit results to the location supplied. By default, results are returned for the default (main) location associated with the merchant.</param> /// <param name="total">Optional parameter: The exact amount in the total_money for a `Payment`.</param> /// <param name="last4">Optional parameter: The last 4 digits of `Payment` card.</param> /// <param name="cardBrand">Optional parameter: The brand of `Payment` card. For example, `VISA`</param> /// <param name="limit">Optional parameter: Maximum number of results to be returned in a single page. It is possible to receive fewer results than the specified limit on a given page. If the supplied value is greater than 100, at most 100 results will be returned. Default: `100`</param> /// <return>Returns the Models.ListPaymentsResponse response from the API call</return> public async Task <Models.ListPaymentsResponse> ListPaymentsAsync( string beginTime = null, string endTime = null, string sortOrder = null, string cursor = null, string locationId = null, long?total = null, string last4 = null, string cardBrand = null, int?limit = null, CancellationToken cancellationToken = default) { //the base uri for api requests string _baseUri = config.GetBaseUri(); //prepare query string for API call StringBuilder _queryBuilder = new StringBuilder(_baseUri); _queryBuilder.Append("/v2/payments"); //process optional query parameters ApiHelper.AppendUrlWithQueryParameters(_queryBuilder, new Dictionary <string, object>() { { "begin_time", beginTime }, { "end_time", endTime }, { "sort_order", sortOrder }, { "cursor", cursor }, { "location_id", locationId }, { "total", total }, { "last_4", last4 }, { "card_brand", cardBrand }, { "limit", limit } }, 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", userAgent }, { "accept", "application/json" }, { "Square-Version", config.SquareVersion } }; //prepare the API call request to fetch the response HttpRequest _request = GetClientInstance().Get(_queryUrl, _headers); if (HttpCallBack != null) { HttpCallBack.OnBeforeHttpRequestEventHandler(GetClientInstance(), _request); } _request = await authManagers["default"].ApplyAsync(_request).ConfigureAwait(false); //invoke request and get response HttpStringResponse _response = await GetClientInstance().ExecuteAsStringAsync(_request, cancellationToken).ConfigureAwait(false); HttpContext _context = new HttpContext(_request, _response); if (HttpCallBack != null) { HttpCallBack.OnAfterHttpResponseEventHandler(GetClientInstance(), _response); } //handle errors defined at the API level base.ValidateResponse(_response, _context); var _responseModel = ApiHelper.JsonDeserialize <Models.ListPaymentsResponse>(_response.Body); _responseModel.Context = _context; return(_responseModel); }
/// <summary> /// 登录成功写入缓存 /// </summary> /// <param name="operatorModel"></param> public void AddCurrent(OperatorModel operatorModel) { //写入Cookie ApiHelper.WriteCookie(PlatPublicConfiger.PlatAdminCookieName, ApiHelper.InverseEncode(ApiHelper.JsonSerial(operatorModel)), 1440); }
/// <summary> /// Create JSON-encoded multipart content from input. /// </summary> internal static MultipartContent CreateJsonEncodedMultipartContent(object input, Dictionary <string, IReadOnlyCollection <string> > headers) { return(new MultipartByteArrayContent(Encoding.ASCII.GetBytes(ApiHelper.JsonSerialize(input)), headers)); }
/// <summary> /// 移除管理员信息 /// </summary> public void RemoveCurrent() { ApiHelper.RemoveCookie(PlatPublicConfiger.PlatAdminCookieName); }
public UnitTest() { ApiHelper.InitializeClient(); }
public HospitalService(IConfiguration configuration) { _apiHelper = new ApiHelper(configuration["ApiClient:ApiUrl"]); }
public void TestCreateSessionFromDeviceToken_Unvalidated_After() { using (var _server = new UnitTestSkyDoxServer(1344)) { DoxApi doxApi = new DoxApi(_apiUrl); _server.NextResponse.Enqueue(MockResponse.user_sessions_SuccessDeviceTokenUnvalidated); _server.NextResponse.Enqueue(MockResponse.current_user_NotValidated); string user = string.Format(_rootEmail, "unvalidated-personal"); ApiHelper apiHelper = new ApiHelper(); var session = doxApi.CreateSessionFromPassword(user, "Workshare1", apiHelper); Assert.IsNotNullOrEmpty(session.Credentials.DeviceToken); session = doxApi.CreateSessionFromDeviceToken(user, session.Credentials.DeviceToken, apiHelper); Assert.NotNull(session); } }
public FileUploadManageService(IConfiguration configuration) { _apiHelper = new ApiHelper(configuration["ApiClient:ApiUrl"]); }
public void TestSignupAsAUserThatAlreadyExistsAndIsValidated() { ApiHelper apiHelper = new ApiHelper(); string password = "******"; string user = string.Format(_rootEmail, "validated-personal"); Assert.IsFalse(apiHelper.RegisterNewUser(_apiUrl, user, password)); }