public ChatClient(string Url, string Client, string Channel, RestfulClient HttpClient) { this.Url = Url; this.Client = Client; this.Channel = Channel; this.HttpClient = HttpClient; }
public async void UpdateUserFCM(string fcm) { using (var client = new RestfulClient()) { UserDTO user = DataBase.Instance.Query <UserDTO>().FirstOrDefault(); user.FCM = fcm; user.ISFCMDeprecated = true; DataBase.Instance.Update(user); if (user.IsRegistered) { RegisterUserDTO register = new RegisterUserDTO() { FcmId = user.FCM }; ResponseModel model = await _rc.PostDataAsync(PostActionMethods.UpdateFCM, register); if (model.IsSuccessStatusCode) { user.ISFCMDeprecated = false; DataBase.Instance.Update(user); } } } }
public static RestfulClient ProvideRestClient(IServiceProvider serviceProvider) { if (serviceProvider is null) { throw new ArgumentNullException(nameof(serviceProvider)); } var contextAccessor = serviceProvider.GetService <IHttpContextAccessor>(); if (contextAccessor is null) { throw new NullReferenceException(nameof(contextAccessor)); } var context = contextAccessor.HttpContext; if (context is null) { throw new NullReferenceException(nameof(context)); } var client = new RestfulClient(); var token = context.RetrieveCookieAuthToken(); if (!string.IsNullOrEmpty(token)) { client.Authenticate(token); } return(client); }
private async void Button_Click(object sender, RoutedEventArgs e) { if (userpassword.Password != passwordConfirm.Password) { MainWindow mainWindow = MainWindow.GetInstance(); mainWindow.notifyIcon.BalloonTipTitle = Env.PROJECT_NAME; mainWindow.notifyIcon.BalloonTipText = "两次密码输入不一致"; mainWindow.notifyIcon.ShowBalloonTip(1); } else { UserRegisterRequest userRegister = new UserRegisterRequest(userName.Text, userpassword.Password, signature.Text); RestfulClient <string> restfulClient = new RestfulClient <string>(userRegister); string userId = await restfulClient.GetResponse(); if (userId != null) { MainWindow mainWindow = MainWindow.GetInstance(); mainWindow.notifyIcon.BalloonTipTitle = Env.PROJECT_NAME; mainWindow.notifyIcon.BalloonTipText = "注册成功"; mainWindow.notifyIcon.ShowBalloonTip(1); UserMain.GetInstance().Close(); MainWindow.GetInstance().Show(); } } }
public void XliteHistory() { using (var dbConn = Helpers.OrmliteConnection.openConn()) { var lastDate = dbConn.GetScalar <DateTime>("SELECT TOP 1 CallDate FROM DC_Telesales_Xlite Order By Id DESC").ToString("yyyy-MM-dd HH:mm:ss"); string currentDate = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); var data = RestfulClient.POST(ConfigurationManager.AppSettings["XliteAPIHistory"].ToString().Trim() + "?action=outbound&date_from=" + lastDate + "&date_to=" + currentDate + "&user=deca_report&password="******"1811HoaSao@@"), ""); DC_Telesales_Xlite_API listHistory = new DC_Telesales_Xlite_API(); if (!String.IsNullOrEmpty(data)) { JavaScriptSerializer objJavascript = new JavaScriptSerializer { MaxJsonLength = Int32.MaxValue, RecursionLimit = 100 }; listHistory = objJavascript.Deserialize <DC_Telesales_Xlite_API>(data); listHistory.data.ForEach(s => { s.CreatedAt = DateTime.Now; s.CreatedBy = "cronXLite"; }); foreach (var item in listHistory.data) { var exist = dbConn.Select <DC_Telesales_Xlite_API>("SELECT * FROM DC_Telesales_Xlite where RecordingFile = {0}", item.recordingfile); if (exist.Count() == 0) { dbConn.Insert(item); } } } } }
private async void loadDataAsync() { RestfulClient <List <CalendarModel> > recommendListRest = new RestfulClient <List <CalendarModel> >("/piazza/most-subscribed"); recommendListRest.AddParameter("size", "500"); RestfulClient <List <CalendarModel> > allListRest = new RestfulClient <List <CalendarModel> >("/piazza/all"); allListRest.AddParameter("size", "500"); this.recommendListData = await recommendListRest.GetResponse(); this.allListData = await allListRest.GetResponse(); Console.Write("ended"); Console.Write(allListData[0]); for (int i = 0; i < this.recommendListData.Count; i++) { this.recommendList.Items.Add(new SqureCard(recommendListData[i])); } for (int i = 0; i < this.allListData.Count; i++) { this.allList.Items.Add(new SqureCard(allListData[i])); } }
public void Go_To_Next_Until_Get_To_End_Test(string mazeId, string state) { var stubPathService = new Mock <IPathService>(); var server = FluentMockServer.Start(null, false); var client = new RestfulClient(server.Urls.Select(u => string.Concat(new Uri(u))).First() + "pony-challenge/maze", true); IGameService gameService = new GameService(client); var resultResponseMove = new ResponseMove(); var pathWay = new Model.Robot.PathWay(0, new List <MoveType> { MoveType.West }); stubPathService.Setup(fm => fm.FindMoves(mazeId)).Returns(pathWay); var responseBody = new Dictionary <string, object> { ["state"] = "active", ["state-result"] = "Move accepted" }; server.Given(Request.Create().UsingPost()) .RespondWith(Response.Create() .WithStatusCode(200) .WithHeader("content-type", "application/json; charset=utf-8") .WithBodyAsJson(responseBody, Encoding.UTF8)); var roboteEngine = new RobotEngine(gameService, stubPathService.Object); var result = roboteEngine.GotoNext(mazeId); Assert.AreEqual(result.State, "active"); }
protected void Download(string url, string fileName) { _handler.Handle(() => { _restfulClient = _restfulClient ?? new RestfulClient(); return(_restfulClient.Download(url, fileName)); }); }
private async void getCreated() { RestfulClient <List <TodayResponse> > restful = new RestfulClient <List <TodayResponse> >("/custom/created"); this.created = await restful.GetResponse(); createCount.Content = this.created.Count; }
public async Task GetAsync_TestDefaultResponse() { var messageHandler = FakeResponseHandler.Create(HttpStatusCode.OK, endpoint, null); var client = new RestfulClient(endpoint, messageHandler); var testObject = await client.GetAsync <TestObject>(endpoint); Assert.AreEqual(default(TestObject), testObject); }
public void First() { Assert.IsTrue(true); var client = new RestfulClient("https://jsonplaceholder.typicode.com/"); var result = client.Get <List <Post> >("posts"); Assert.AreEqual(100, result.Count); }
private void btn_comment_Click(object sender, RoutedEventArgs e) { if (!edit_content.Text.Equals("")) { AddCommentRequest request = new AddCommentRequest(calendarId, edit_content.Text); RestfulClient <String> detailRestful = new RestfulClient <String>(request); detailRestful.GetResponse(); initCommentViewAsync(); } }
public async Task GetAsync_TestEmptyResponse() { var messageHandler = FakeResponseHandler.Create(HttpStatusCode.OK, endpoint); var client = new RestfulClient(endpoint, messageHandler); var testObject = await client.GetAsync <Empty>(endpoint); Assert.IsTrue(testObject.IsSuccessStatusCode); Assert.AreEqual("OK", testObject.ReasonPhrase); Assert.AreEqual(HttpStatusCode.OK, testObject.StatusCode); }
private async Task initDetailView() { DetailRequest detailRequest = new DetailRequest(calendarId); RestfulClient <DetailResponse> detailRestful = new RestfulClient <DetailResponse>(detailRequest); detailResponse = await detailRestful.GetResponse(); this.img_picture.Source = new BitmapImage(new Uri(detailResponse.picture, UriKind.Absolute)); txt_author.Content = detailResponse.creatorName; txt_content.Content = detailResponse.description; txt_title.Content = detailResponse.title; }
private async Task initCommentViewAsync() { GetComment commentRequest = new GetComment(calendarId); RestfulClient <List <CommentModel> > commentRestful = new RestfulClient <List <CommentModel> >(commentRequest); comment = await commentRestful.GetResponse(); lv_comment.Items.Clear(); for (int i = 0; i < comment.Count; i++) { lv_comment.Items.Add(new CommentItem(comment[i].userName, comment[i].comment, "2018-1-1", comment[i].userAvatar)); } }
public void InitRestfulClient() { RestfulClient = new RestfulClient(); var password = RestfulServer.Context.LocalAuthenticationPassword; if (password != null) { RestfulClient.DefaultRequestHeaders.Add( LocalAuthenticationMiddleware.PasswordHeaderKey, password ); } }
public async void loadToday(long calendarId) { // 单个黄历信息的请求 GetTodayById request = new GetTodayById(calendarId); RestfulClient <TodayResponse> restful = new RestfulClient <TodayResponse>(request); TodayResponse rsp = await restful.GetResponse(); if (rsp != null) { this.tResponse = rsp; refresh(); } }
protected TResponse Get <TRequest, TResponse>(TRequest request) where TRequest : APIRequestBodyBase <TRequest> where TResponse : APIResponseBodyBase <TResponse> { var result = _handler.Handle(() => { _restfulClient = _restfulClient ?? new RestfulClient(); return(_restfulClient.DoGet(request.Url, request.ToString(), request.Headers)); }); var response = APIResponseBodyBase <TResponse> .Deserialize(result); return(response); }
public async void loadTodayList() { // 列表的请求 GetSubscribedToday request = new GetSubscribedToday(); RestfulClient <List <TodayResponse> > restful = new RestfulClient <List <TodayResponse> >(request); List <TodayResponse> rsp = await restful.GetResponse(); if (rsp != null) { this.tList = rsp; refresh(); } }
public async Task GetAsync_TestRequestFailure() { var messageHandler = FakeResponseHandler.Create(HttpStatusCode.NotFound, endpoint); var client = new RestfulClient(endpoint, messageHandler); try { await client.GetAsync <TestObject>(endpoint); } catch (RestfulClientException ex) { Assert.AreEqual(HttpStatusCode.NotFound, ex.StatusCode); Assert.IsNull(ex.ResponseContent); Assert.IsTrue(ex.Message.Contains("RestfulClient received unsuccessful response")); } }
public async Task PatchAsync_TestRequestAndResponse() { var messageHandler = FakeResponseHandler.Create(HttpStatusCode.OK, endpoint, payload); var client = new RestfulClient(endpoint, messageHandler); var testObject = await client.PatchAsync <TestObject>(endpoint, payload); Assert.IsNotNull(testObject); Assert.AreEqual(1, messageHandler.Requests.Count); var request = messageHandler.Requests.FirstOrDefault(); Assert.AreEqual(new HttpMethod("PATCH"), request.Method); Assert.AreEqual(new Uri(endpoint), request.RequestUri); Assert.IsNotNull(request.Content); }
public void Print(string mazeId) { var server = FluentMockServer.Start(null, false); var client = new RestfulClient(server.Urls.Select(u => string.Concat(new Uri(u))).First() + $"pony-challenge/maze", true); IGameService gameService = new GameService(client); server.Given(Request.Create().UsingGet()) .RespondWith(Response.Create() .WithStatusCode(200) .WithHeader("content-type", "application/json; charset=utf-8") .WithBody("+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+\n| | | | |\n+ +---+ + +---+---+---+ + +---+---+ +---+---+ +\n| | | | | | |\n+---+ +---+ +---+---+ +---+---+ +---+---+---+---+---+\n| | | | | | |\n+ +---+ + +---+ + +---+---+---+ + + +---+ +\n| | | | | | | | |\n+ +---+ +---+ + +---+ +---+---+---+---+---+ + +\n| | | | P | | | D | | |\n+ +---+---+ + +---+ + + +---+ +---+ + + +\n| | | | | | | | | |\n+ +---+ +---+---+ +---+---+ + +---+ + + +---+\n| | | | | | | | |\n+---+ +---+ + +---+ + + + + +---+---+ + +\n| | | | | | | | | | | |\n+ + + +---+---+ +---+---+ + + + + +---+ +\n| | | | | | | | |\n+ + +---+---+ +---+ +---+ + +---+---+---+---+ +\n| | | | | | | | |\n+ +---+ +---+---+ +---+ + + +---+---+ + + +\n| | | | | | | |\n+---+---+---+ +---+---+---+---+ +---+---+ + + + +\n| | | | | | | |\n+ + + +---+---+ +---+---+---+---+---+ +---+---+---+\n| | | | |\n+ +---+---+---+---+---+ +---+---+---+ + +---+---+ +\n| | | | | | | | | |\n+ + + + + +---+---+ + +---+ +---+ + + +\n| | | | E | |\n+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+")); var gameServiceobj = gameService.Print(mazeId); Assert.IsTrue(gameServiceobj.Contains("+")); }
public async Task GetAsync() { //arrange var rest = Substitute.For<IRestClient>(); var client = new RestfulClient(rest); IEnumerable<Ad> ads = new List<Ad>(); rest.GetAsync(Arg.Any<HttpConfiguration>(), Arg.Any<Func<HttpResponseMessage, IEnumerable<Ad>>>()) .Returns(Task.FromResult(ads)); //act var ret = await client.GetAsync(new List<long> { 1 }); //assert rest.Received(1).GetAsync( Arg.Is<HttpConfiguration>(x => x.Route == "api/ad"), Arg.Any<Func<HttpResponseMessage, IEnumerable<Ad>>>()); }
private void btn_subscribe_Click(object sender, RoutedEventArgs e) { if (btn_subscribe.Content.ToString() == "未订阅") { SubscribeRequest subscribeRequest = new SubscribeRequest(calendarId); RestfulClient <String> request = new RestfulClient <String>(subscribeRequest); request.GetResponse(); btn_subscribe.Content = "已订阅"; } else { UnsubscribeReques unsubscribeRequest = new UnsubscribeReques(calendarId); RestfulClient <String> request = new RestfulClient <String>(unsubscribeRequest); request.GetResponse(); btn_subscribe.Content = "未订阅"; } }
private async void loadDataAsync() { RestfulClient <List <TodayResponse> > subListRest = new RestfulClient <List <TodayResponse> >("/calendar/subscribed"); subListRest.AddParameter("size", "500"); this.subscribeListData = await subListRest.GetResponse(); Console.WriteLine(subscribeListData.Count); for (int i = 0; i < this.subscribeListData.Count; i++) { if (subscribeListData[i].calendarPicture != null) { this.subscribeList.Items.Add(new SqureCard(subscribeListData[i])); } } }
/// <summary> /// 根据绑定中的协议类型调用不同的实现方法 /// </summary> /// <param name="state"></param> /// <returns></returns> private static JN.ESB.Schemas.务响应 CallService(CallState callState) { switch (callState.Binding.BindingType) { case (int)BindingType.WebService: return(SoapClient.CallWebService(callState)); case (int)BindingType.REST: return(RestfulClient.CallRestfulService(callState)); case (int)BindingType.ASHX: return(HandlerClient.CallAshxService(callState)); case (int)BindingType.WCF_HTTP: return(WcfClient.CallWcfService(callState)); default: throw LogUtil.ExceptionAndLog(callState, "未知的绑定类型", callState.Binding.BindingType.ToString(), callState.Binding, callState.Request); } }
public async Task GetAsync_TestAdditionalRequestHeaders() { var messageHandler = FakeResponseHandler.Create(HttpStatusCode.OK, endpoint, payload); var client = new RestfulClient(endpoint, messageHandler); var headers = new Dictionary <string, string>() { { testHeader.Key, testHeader.Value } }; var testObject = await client.GetAsync <TestObject>(endpoint, headers); var request = messageHandler.Requests.FirstOrDefault(); Assert.IsTrue(request.Headers.Contains(testHeader.Key)); var testHeaderValues = request.Headers.GetValues(testHeader.Key); Assert.AreEqual(1, testHeaderValues.Count()); Assert.AreEqual(testHeader.Value, testHeaderValues.FirstOrDefault()); }
protected async Task <TResponse> PostAsync <TRequest, TResponse>(TRequest request) where TRequest : APIRequestBodyBase <TRequest> where TResponse : APIResponseBodyBase <TResponse> { var result = await _handler.HandleAsync(() => { _restfulClient = _restfulClient ?? new RestfulClient(); return(_restfulClient.PostAsync(request.Url, request.ContentType, request.Headers, request.ToString(), request.SecurityProtocol, request.TimeOut, request.UseSecurity)); }); var response = APIResponseBodyBase <TResponse> .Deserialize(result); return(response); }
private async void Button_Click(object sender, RoutedEventArgs e) { UserLoginRequest userLoginRequest = new UserLoginRequest(txtUserName.Text, txtPassword.Password); RestfulClient <UserLoginResponse> restful = new RestfulClient <UserLoginResponse>(userLoginRequest); UserLoginResponse response = await restful.GetResponse(); if (response != null) { ShowSystemNotice("Today", "登录成功,欢迎 " + response.user.name, 10); IFormatter formatter = new BinaryFormatter(); Stream stream = new FileStream("./user.me", FileMode.OpenOrCreate, FileAccess.Write, FileShare.None); formatter.Serialize(stream, response); stream.Close(); this.Hide(); new NewMasterWindow().Show(); } }
/// <summary> /// 发送损益单到数据交换中心 /// </summary> /// <param name="adjustInfo"></param> private bool SendAdjust(AdjustInfo adjustInfo) { var result = RestfulClient.PostJson <string>(ConfigurationManager.AppSettings["AdjustRestfulUrl"], "causticExcessive", adjustInfo, (message) => { WriteLog(message, "SendRequest"); }); var success = result.Code == RestfulCode.Success;//200成功 if (success) { AdjustDA.UpdateAdjustStatus(adjustInfo.SysNo); //记录成功日志 WriteLog("损益单【" + adjustInfo.AdjustID + "】[" + adjustInfo.ItemCode + "]发送至数据交换中心成功", "Success"); } else { //记录失败日志 WriteLog("损益单【" + adjustInfo.AdjustID + "】[" + adjustInfo.ItemCode + "]发送至数据交换中心失败【" + SerializationUtility.JsonSerialize(result) + "】", "Failed"); } return(success); }
/// <summary> /// 发送商品信息到数据交换中心 /// </summary> /// <param name="productInfo"></param> private bool SendProduct(ProductInfo productInfo) { var result = RestfulClient.PostJson <string>(ConfigurationManager.AppSettings["ProductRestfulUrl"], "addItem", productInfo, (message) => { WriteLog(message, "SendRequest"); }); var success = result.Code == RestfulCode.Success;//200成功 if (success) { ProductDA.UpdateProductStatus(productInfo.SysNo); //记录成功日志 WriteLog("商品【" + productInfo.ItemCode + "】发送至数据交换中心成功", "Success"); } else { //记录失败日志 WriteLog("商品【" + productInfo.ItemCode + "】发送至数据交换中心失败【" + SerializationUtility.JsonSerialize(result) + "】", "Failed"); } return(success); }