/// <summary> /// 获取部门列表【未完成】 /// </summary> /// <param name="access_token"></param> /// <param name="id">部门id。获取指定部门及其下的子部门。 如果不填,默认获取全量组织架构</param> /// <returns></returns> public static async Task <(bool isSuccess, string msg)> ListAsync(string access_token, int?id = null) { var url = $"https://qyapi.weixin.qq.com/cgi-bin/department/list?access_token={access_token}&id={id}"; var httpRet = await HttpClientManager.GetAsync(url); return(true, httpRet); }
/// <summary> /// 创建部门【已完成】 /// </summary> /// <param name="access_token">调用接口凭证</param> /// <param name="name">部门名称。长度限制为1~64个字节</param> /// <param name="parentid">父部门id,32位整型</param> /// <param name="order">在父部门中的次序值。order值大的排序靠前。有效的值范围是[0, 2^32)</param> /// <returns></returns> public static async Task <(bool isSuccess, string msg, int id)> CreateAsync(string access_token, string name, int parentid, int order = 0) { var url = $"https://qyapi.weixin.qq.com/cgi-bin/department/create?access_token={access_token}"; var content = JsonConvert.SerializeObject(new { name, parentid, order, }); var httpRet = await HttpClientManager.PostAsync(url, content); var json = JObject.Parse(httpRet); var errcode = json.Value <long>("errcode"); var errmsg = json.Value <string>("errmsg"); if (errcode == 0) { return(true, errmsg, json.Value <int>("id")); } else { return(false, errmsg, 0); } }
public async Task SendHttpRequestAsync_GIVEN_Invalid_AuthenticationHeaderValue_Input_RETURNS_Valid_StringNotNull() { // Arrange. var httpClientFactory = Substitute.For <IHttpClientFactory>(); var responseObject = new { Name = "Test", Surname = "Smith" }; var fakeMsgHandler = new FakeHttpMessageHandler(JsonConvert.SerializeObject(responseObject)); var fakeHttpClient = new HttpClient(fakeMsgHandler); httpClientFactory.CreateClient(Arg.Any <string>()).Returns(info => fakeHttpClient); var httpClientManager = new HttpClientManager(httpClientFactory); var acceptHeader = new Dictionary <string, string> { { "Accept", "application/json" } }; var requestContent = new { ReferenceNumber = "Test1234" }; var serializedRequest = JsonConvert.SerializeObject(requestContent); var httpContent = new StringContent(serializedRequest, Encoding.UTF8, "application/json"); // Act. var actual = await httpClientManager.SendHttpRequestAsync(HttpMethod.Post, null, acceptHeader, "http://test.co.za", httpContent, CancellationToken.None); // Assert. Assert.NotNull(actual); Assert.AreEqual("{\"Name\":\"Test\",\"Surname\":\"Smith\"}", actual); }
public IActionResult Error() { var ex = HttpContext.Features.Get <IExceptionHandlerPathFeature>().Error; ErrorViewModel model = new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier }; model.IsAdmin = CookieUtil.IsAdmin(HttpContext); model.Ex = ex; LineUtil.PushMe($"【エラー発生】\n" + $"{ex.ToString().Split(Environment.NewLine)[0]}\n" + $"{ex.ToString().Split(Environment.NewLine)[1]}", HttpClientManager.GetInstance()); Log log = new Log { LogDate = DateTime.Now , LogType = LogType.EXCEPTION , LogDetail = ex.ToString() , UserId = CookieUtil.IsAdmin(HttpContext).ToString() }; _context.Log.Add(log); _context.SaveChanges(); return(View(model)); }
public IActionResult WorkingCheck(int?interval) { if (!CookieUtil.IsAdmin(HttpContext)) { return(NotFound()); } if (jafleet.WorkingCheck.Processing) { LineUtil.PushMe("WorkingCheck 二重起動を検出", HttpClientManager.GetInstance()); return(Content("Now Processing!!")); } _ = Task.Run(() => { using (var serviceScope = _services.CreateScope()) { IEnumerable <AircraftView> targetReg; using (var context = serviceScope.ServiceProvider.GetService <jafleetContext>()) { #if DEBUG targetReg = context.AircraftView.Where(a => a.RegistrationNumber == "JA26LR").AsNoTracking().ToArray(); #else targetReg = context.AircraftView.Where(a => a.OperationCode != OperationCode.RETIRE_UNREGISTERED).AsNoTracking().ToArray().OrderBy(r => Guid.NewGuid()); #endif var check = new WorkingCheck(targetReg, interval ?? 15); _ = check.ExecuteCheckAsync(); } } }); return(Content("WorkingCheck Launch!")); }
public async Task WhenValidInputPassed_ReturnListofDeals() { //Arrage var productTypes = new List <string> { "Broadband" }; var speed = "17"; var data = JsonConvert.SerializeObject(TestdataGenerator.CreateFakeBroadbandResult()); var responseMessage = new HttpResponseMessage() { StatusCode = HttpStatusCode.OK, Content = new StringContent(data, System.Text.Encoding.UTF8, "application/json"), }; var messageHandler = new FakeHttpMessageHandler(responseMessage); var _httpClientManager = new HttpClientManager(messageHandler); //Act var response = await _httpClientManager.GetBroadbandDeals(It.IsAny <string[]>(), It.IsAny <string>()); // Assert Assert.IsTrue(response != null && response.Deals != null); Assert.IsTrue(response.Deals.Count > 0); Assert.IsTrue(response.Result != null && response.Result.ResultStatus == ResultStatus.Success); }
private void ExecuteGetJobsDto(OrchestartorModel model) { string url = $"https://{model.HostName}/odata/Jobs"; var task = HttpClientManager.ExecuteGetAsync <OrcJobsDto>(url); ConsoleUtil.PrintLoadingString <OrcJobsDto>(task); foreach (var item in task.Result.value) { CommandManager.ResultList.Add(DateTime.Now.ToString("ddss.ffffff").ToString(), $"{item.Id},{item.Key},{item.Source},{item.Info},{item.StartTime}"); System.Threading.Thread.Sleep(100); } ConsoleUtil.PrintTable <OrcJobsDto.Value>(task.Result.value.ToList(), new List <string>() { nameof(OrcJobsDto.Value.Id), nameof(OrcJobsDto.Value.Key), nameof(OrcJobsDto.Value.Source), nameof(OrcJobsDto.Value.Info), nameof(OrcJobsDto.Value.StartTime) }); CommandManager.ResultList = new Dictionary <string, string>(); }
public async Task SendHttpRequestAsync_GIVEN_Invalid_Url_Input_RETURNS_Null(string url) { // Arrange. var httpClientFactory = Substitute.For <IHttpClientFactory>(); var responseObject = new { Name = "Test", Surname = "Smith" }; var fakeMsgHandler = new FakeHttpMessageHandler(JsonConvert.SerializeObject(responseObject)); var fakeHttpClient = new HttpClient(fakeMsgHandler); httpClientFactory.CreateClient(Arg.Any <string>()).Returns(info => fakeHttpClient); var httpClientManager = new HttpClientManager(httpClientFactory); var authorizationHeader = new AuthenticationHeaderValue("Basic", "sdfdsf"); var acceptHeader = new Dictionary <string, string> { { "Accept", "application/json" } }; var requestContent = new { ReferenceNumber = "Test1234" }; var serializedRequest = JsonConvert.SerializeObject(requestContent); var httpContent = new StringContent(serializedRequest, Encoding.UTF8, "application/json"); // Act. var actual = await httpClientManager.SendHttpRequestAsync(HttpMethod.Post, authorizationHeader, acceptHeader, url, httpContent, CancellationToken.None); // Assert. Assert.IsNull(actual); }
private async Task <Testcase> GetTestcaseAsync(int i, int serial) { Testcase testcase = new Testcase(); if (isSample) { testcase.Serial = samples[i].Serial; testcase.ProblemId = samples[i].ProblemId; testcase.In = samples[i].In; testcase.Out = samples[i].Out; } else { testcase = await HttpClientManager.ExecuteGetJsonAsync <Testcase>(string.Format(FIND_BY_PROBLEM_ID_TESTCASE, probrem.id, serial)); if (testcase.In.Contains("(terminated because of the limitation)")) { testcase.In = await HttpClientManager.ExecuteGetStringAsync(string.Format(FIND_BY_PROBLEM_ID_TESTCASE_ALT_IN, probrem.id, serial)); } if (testcase.Out.Contains("(terminated because of the limitation)")) { testcase.Out = await HttpClientManager.ExecuteGetStringAsync(string.Format(FIND_BY_PROBLEM_ID_TESTCASE_ALT_OUT, probrem.id, serial)); } } return(testcase); }
private void ExecuteGetRobotsDto(OrchestartorModel model) { string url = $"https://{model.HostName}/odata/Robots"; var task = HttpClientManager.ExecuteGetAsync <OrcRobotDto>(url); ConsoleUtil.PrintLoadingString <OrcRobotDto>(task); foreach (var item in task.Result.value) { CommandManager.ResultList.Add(DateTime.Now.ToString("ddss.ffffff").ToString(), $"{item.Id},{item.Name},{item.MachineName},{item.Password},{item.RobotEnvironments},{item.Username}"); System.Threading.Thread.Sleep(100); } ConsoleUtil.PrintTable <OrcRobotDto.Value>(task.Result.value.ToList(), new List <string>() { nameof(OrcRobotDto.Value.Id), nameof(OrcRobotDto.Value.Name), nameof(OrcRobotDto.Value.MachineName), nameof(OrcRobotDto.Value.Password), nameof(OrcRobotDto.Value.RobotEnvironments), nameof(OrcRobotDto.Value.Username) }); CommandManager.ResultList = new Dictionary <string, string>(); }
public async Task<BitrixNotifications> GetBxNotifications(string access_token) { var http = new HttpClientManager(); var bx = new BXManager(); var notifs = await http.GetAndDeserialize<BitrixNotifications>(bx.bxRestUrl + "im.counters.get?auth=" + access_token,"result=>TYPE"); return notifs; }
private async void BtnConnect_ClickAsync(object sender, EventArgs e) { if (txtNo.Text == string.Empty) { return; } ClearDisplayArea(); probrem = await HttpClientManager.ExecuteGetXMLAsync <Probrem>(string.Format(API_AOJ_OLD, ID)); probrem.id = probrem.id.Replace("\n", string.Empty); probrem.name = probrem.name.Replace("\n", string.Empty); var responce2 = await HttpClientManager.ExecuteGetJsonAsync <Probrem2>(string.Format(API_AOJ_NEW, ID)); var parser = new HtmlParser(); var doc = parser.ParseDocument(responce2.html); txtTitle.Text = string.Format("AOJ {0} ({1} : {2})", ID, probrem.name, doc.QuerySelectorAll("h1")[0].TextContent); string text = ""; using (StreamReader sr = new StreamReader("ContentsTemplate.txt", Encoding.GetEncoding("UTF-8"))) { text = sr.ReadToEnd(); } txtContents.Text = string.Format(text, ID); }
public void UploadBatch(NBatchInfo batch) { NResultInfo nResultInfo = new NResultInfo(); nResultInfo.Status = EResultStatus.eSuccess; NResultInfo result; try { string transMode = AppContext.GetInstance().Config.GetConfigParamValue("NetSetting", "TransMode"); //batch.TransMode = (ETransMode)Enum.Parse(typeof(ETransMode), transMode); if (transMode.Equals(ConstString.TRANSMODE_FULL)) { HttpClientManager.FullUpload(batch); //完全方式提交 } else if (transMode.Equals(ConstString.TRANSMODE_BROKE)) { HttpClientManager.BroekUpload(batch); //断点方式提交 } this.ReportMsg(ENetTransferStatus.Success, batch.BatchNO, "", 0.0, 0.0); } //catch (WebException ex) //{ // this.ReportMsg(ENetTransferStatus.Error, batch.BatchNO, ExceptionHelper.GetFirstException(ex).Message, 0.0, 0.0); //} catch (Exception e) { this.ReportMsg(ENetTransferStatus.Error, batch.BatchNO, ExceptionHelper.GetFirstException(e).Message, 0.0, 0.0); } //this._uploadresult = nResultInfo; //result = nResultInfo; //return result; }
public async Task SendHttpRequestAsync_GIVEN_Valid_Input_HttpMethod_Post_GetAccessTokenAsync_RETURNS_Valid_StringNotNull() { // Arrange. var httpClientFactory = Substitute.For <IHttpClientFactory>(); var httpClientManager = new HttpClientManager(httpClientFactory); httpClientFactory.CreateClient(Arg.Any <string>()).Returns(info => new HttpClient()); var headers = new Dictionary <string, string>(); var keyValueContent = new Dictionary <string, string> { { "grant_type", "client_credentials" }, { "client_id", "push-user" }, { "client_secret", "bNvrT3EsEnPwDvwy46wVyev7DHR4f86e32LVZBJk6ej" } }; var httpContent = new FormUrlEncodedContent(keyValueContent); httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded"); // Act. var actual = await httpClientManager.SendHttpRequestAsync(HttpMethod.Post, null, headers, "https://drivewithdialstable.retrotest.co.za/api/v1/token", httpContent, CancellationToken.None); // Assert. Assert.IsNotNull(actual); }
public async Task SendHttpRequestAsync_GIVEN_Valid_Input_HttpMethod_Post_FormUrlEncodedContent_RETURNS_Valid_StringNotNull() { // Arrange. var httpClientFactory = Substitute.For <IHttpClientFactory>(); var httpClientManager = new HttpClientManager(httpClientFactory); httpClientFactory.CreateClient(Arg.Any <string>()).Returns(info => new HttpClient()); var authorizationHeader = new AuthenticationHeaderValue("Basic", "sdfdsf"); var acceptHeader = new Dictionary <string, string> { { "Accept", "application/json" }, { "User-Agent", "HttpClientManagerIntegrationTests" } }; var keyValueContent = new Dictionary <string, string> { { "grant_type", "client_credentials" }, { "client_id", "push-user" }, { "client_secret", "SECRET" } }; var httpContent = new FormUrlEncodedContent(keyValueContent); // Act. var actual = await httpClientManager.SendHttpRequestAsync(HttpMethod.Post, authorizationHeader, acceptHeader, "https://httpbin.org/post", httpContent, CancellationToken.None); // Assert. Assert.IsNotNull(actual); }
public IActionResult Send(MessageModel model) { LineUtil.PushMe("【JA-Fleet from web】\n" + $"名前:{model.Name}\n" + $"返信先:{model.Replay}\n" + $"{model.Message}", HttpClientManager.GetInstance()); Task.Run(() => { using (var serviceScope = _services.CreateScope()) { using (var context = serviceScope.ServiceProvider.GetService <jafleetContext>()) { var m = new Message { Sender = model.Name, MessageDetail = model.Message, ReplayTo = model.Replay, MessageType = Commons.Constants.MessageType.WEB, RecieveDate = DateTime.Now }; context.Messages.Add(m); context.SaveChanges(); } } }); return(Content("OK")); }
/// <summary> /// 获取部门成员详情 /// </summary> /// <param name="access_token">调用接口凭证</param> /// <param name="department_id">获取的部门id</param> /// <param name="fetch_child">1/0:是否递归获取子部门下面的成员</param> public static async Task <ListUserResult> ListAsync(string access_token, string department_id, int fetch_child) { var url = $"https://qyapi.weixin.qq.com/cgi-bin/user/list?access_token={access_token}&department_id={department_id}&fetch_child={fetch_child}"; var result = await HttpClientManager.GetAsync <ListUserResult>(url); return(result); }
static void Main(string[] args) { Console.WriteLine("Please key-in the words you want display at WebAPI browser page:"); string userInputString = Console.ReadLine(); string url = ""; HttpClientManager httpClientConnector = new HttpClientManager(); string responseFromWebAPI = httpClientConnector.Post(url, userInputString); }
public IActionResult Store(EditModel model) { try{ DateTime storeDate = DateTime.Now; string reg = model.Aircraft.RegistrationNumber; var origin = _context.Aircraft.AsNoTracking().Where(a => a.RegistrationNumber == reg).FirstOrDefault(); if (!model.NotUpdateDate || model.IsNew) { model.Aircraft.UpdateTime = storeDate; } model.Aircraft.ActualUpdateTime = storeDate; if (model.IsNew) { model.Aircraft.CreationTime = storeDate; _context.Aircraft.Add(model.Aircraft); } else { if (!model.NotUpdateDate) { //Historyにコピー var ah = new AircraftHistory(); Mapper.Map(origin, ah); ah.HistoryRegisterAt = storeDate; //HistoryのSEQのMAXを取得 var maxseq = _context.AircraftHistory.AsNoTracking().Where(ahh => ahh.RegistrationNumber == ah.RegistrationNumber).GroupBy(ahh => ahh.RegistrationNumber) .Select(ahh => new { maxseq = ahh.Max(x => x.Seq) }).FirstOrDefault(); ah.Seq = (maxseq?.maxseq ?? 0) + 1; _context.AircraftHistory.Add(ah); } _context.Entry(model.Aircraft).State = Microsoft.EntityFrameworkCore.EntityState.Modified; } //デリバリーされたらテストレジはクリア if (!OperationCode.PRE_DELIVERY.Contains(model.Aircraft.OperationCode)) { model.Aircraft.TestRegistration = null; } _context.SaveChanges(); }catch (Exception ex) { model.ex = ex; } model.AirlineList = MasterManager.AllAirline; model.TypeList = MasterManager.Type; model.OperationList = MasterManager.Operation; model.WiFiList = MasterManager.Wifi; string noheadString = string.Empty; if (model.NoHead) { noheadString = "?nohead=" + model.NoHead.ToString(); } //写真を更新 _ = HttpClientManager.GetInstance().GetStringAsync($"http://localhost:5000/Aircraft/Photo/{model.Aircraft.RegistrationNumber}?force=true"); return(Redirect("/E/" + model.Aircraft.RegistrationNumber + noheadString)); }
public async Task <JsonDocument> GetReports([FromBody] Grid grid) { Dictionary <string, object> dict = new Dictionary <string, object>(); //var permission = await new BitrixController().PermissionToWorkgroup(authUser.bx_access_token,workgroupName); //if (!permission) return throwError("თქვენ არ გაქვთ ამ ოპერაციის განხორციელების უფლება"); string credentials = ""; if (authUser.user1C == null || String.IsNullOrEmpty(authUser.user1C.username)) { return(throwError("თქვენ არ გაქვთ ამ ოპერაციის განხორციელების უფლება")); } if (!string.IsNullOrEmpty(authUser.user1C.username)) { credentials = authUser.user1C.username; } if (!string.IsNullOrEmpty(authUser.user1C.password)) { credentials = ":" + authUser.user1C.password; } string base64Cred = Convert.ToBase64String(Encoding.UTF8.GetBytes(credentials)); var httpManager = new HttpClientManager(); httpManager.http.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", base64Cred); var clientsList = await httpManager.GetAndDeserialize <List <dsClient> >("http://188.93.95.179:8081/" + authUser.user1C.username + "/hs/Exchange/Clients"); //var http = new HttpClient(); //HttpResponseMessage balances = await http.GetAsync("http://188.93.95.179:8081/demo/hs/Exchange/ClientsBalances?Client="); //var balancesStr = balances.Content.ReadAsStringAsync().Result; //var balancesList = JsonSerializer.Deserialize<List<dsBalance>>(balancesStr); if (clientsList == null || clientsList[0].uid == null) { return(Success(dict)); } var balancesList = await httpManager.GetAndDeserialize <List <dsBalance> >("http://188.93.95.179:8081/" + authUser.user1C.username + "/hs/Exchange/ClientsBalances"); var list = from b in balancesList join c in clientsList on b.Client equals c.uid into joined from c in joined select new { FullName = c.FullName, c.uid, b.ClientBalanceCur, b.ClientBalanceEq }; dict.Add("Count", list.Count <dynamic>()); dict.Add("Rows", list); return(Success(dict)); }
public HttpRequestInstructions(HttpRequestMessageWrapper request, TimeSpan timeout, Func <HttpResponseMessage, ResultEnvelope <T> > responseTransformer, Guid id, HttpClientManager clientManager = null) { Request = request; Timeout = timeout; ResponseTransformer = responseTransformer; Id = id; ClientManager = clientManager; }
public void SetUp() { var interval = 1000; //if you run all tests, set it 10000+ miliseconds, or use several keys _apiHttpClient = HttpClientManager.GetRateLimitClient(@"https://www.alphavantage.co/query", interval, 7); _connectorReal = new AlphaVantageConnector.AlphaVantageConnector(_apiKeyServiceMock.Object, _apiHttpClient); _alphaVantageServiceReal = new AlphaVantageService(_connectorReal); }
public TestRun GetTestRun(Guid guid) { using (var httpClient = new HttpClient()) { using (var httpClientManager = new HttpClientManager(httpClient)) { var url = string.Format("{0}api/testrunapi?guid={1}", _apiUrl, guid); return(JsonConvert.DeserializeObject <TestRun>(httpClientManager.Get(url))); } } }
private async Task <Response <List <ShiftTemplate> > > CallGetTemplates(string employerId) { var parameters = new Dictionary <string, string> { { "employerId", employerId } }; return(await HttpClientManager.ExecuteGetAsync <List <ShiftTemplate> >("ShiftTemplate/GetTemplates", parameters).ConfigureAwait(false)); }
/// <summary> /// 更新标签名字 /// </summary> /// <param name="access_token"></param> /// <param name="tagid">标签ID</param> /// <param name="tagname">标签名称,长度限制为32个字(汉字或英文字母),标签不可与其他标签重名。</param> /// <returns></returns> public static async Task <ReturnBase> UpdateAsync(string access_token, int tagid, string tagname) { var url = $"https://qyapi.weixin.qq.com/cgi-bin/tag/update?access_token={access_token}"; var content = JsonConvert.SerializeObject(new { tagid, tagname, }); return(await HttpClientManager.PostAsync <ReturnBase>(url, content)); }
private async void btnDelete_Click(object sender, EventArgs e) { // Create a new product Product product = new Product { Name = "Gizmo", Price = 100, Category = "Widgets" }; var result = await HttpClientManager.DeleteProductAsync(product.Id); }
public void TestMethod1() { var contents = new SampleObject() { password = "******", usernameOrEmailAddress = "dummy", tenancyName = "dummy" }; var result = HttpClientManager.ExecutePostAsync <SampleObject>("https://academy2016.uipath.com/api/account/authenticate", contents).Result; Assert.AreEqual("An error has occured", result.ResponceContent); }
public MainForm() { InitializeComponent(); httpClient = new HttpClientManager(); currentClient = new ClientManager(); currentClient.ReceiveMessageHandler += HandleReceivedMessages; f1 = this; currentClient.FindServer(); SignForm SignForm = new SignForm(f1, currentClient); SignForm.ShowDialog(); }
/// <summary> /// 環境変数以外から取得した値を利用して、アクセストークンを取得する。 /// </summary> /// <param name="request"></param> /// <returns></returns> public static async Task <AccessTokenResponce> GetAccessTokenAsync(AccessTokenRequest request) { var url = Settings.URL.AccessTokenUrl; AccessTokenResponce responce = await HttpClientManager.ExecutePostAsync <AccessTokenRequest, AccessTokenResponce>(url, request); //set the bearer value for the next API call. CotohaApiManager.BearerValue = responce.StatusCode == HttpStatusCode.Created ? responce.AccessToken : string.Empty; return(responce); }
/// <summary> /// /// </summary> /// <returns></returns> private static async Task <KeyPhraseExtractResponce> ExecuteKeyPhraseExtractAsync(KeyPhraseExtractRequest request) { return (await HttpClientManager.ExecutePostAsyncWithHeaderValue <KeyPhraseExtractRequest, KeyPhraseExtractResponce> ( URL.KeyPhraseUrl, request, new Dictionary <string, string>() { { "Ocp-Apim-Subscription-Key", AccountInfo.KeyPhraseExtractionKey } } )); }