コード例 #1
0
 public ChatClient(string Url, string Client, string Channel, RestfulClient HttpClient)
 {
     this.Url        = Url;
     this.Client     = Client;
     this.Channel    = Channel;
     this.HttpClient = HttpClient;
 }
コード例 #2
0
        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);
                    }
                }
            }
        }
コード例 #3
0
        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);
        }
コード例 #4
0
ファイル: register.xaml.cs プロジェクト: gitabtion/today_wpf
        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();
                }
            }
        }
コード例 #5
0
        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);
                        }
                    }
                }
            }
        }
コード例 #6
0
ファイル: SqurePage.xaml.cs プロジェクト: gitabtion/today_wpf
        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]));
            }
        }
コード例 #7
0
        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");
        }
コード例 #8
0
 protected void Download(string url, string fileName)
 {
     _handler.Handle(() =>
     {
         _restfulClient = _restfulClient ?? new RestfulClient();
         return(_restfulClient.Download(url, fileName));
     });
 }
コード例 #9
0
ファイル: userInfo.xaml.cs プロジェクト: gitabtion/today_wpf
        private async void getCreated()
        {
            RestfulClient <List <TodayResponse> > restful = new RestfulClient <List <TodayResponse> >("/custom/created");

            this.created = await restful.GetResponse();

            createCount.Content = this.created.Count;
        }
コード例 #10
0
        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);
        }
コード例 #11
0
        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);
        }
コード例 #12
0
 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();
     }
 }
コード例 #13
0
        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);
        }
コード例 #14
0
        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;
        }
コード例 #15
0
        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));
            }
        }
コード例 #16
0
ファイル: ServiceContext.cs プロジェクト: arefdsg/tpp-core
        public void InitRestfulClient()
        {
            RestfulClient = new RestfulClient();

            var password = RestfulServer.Context.LocalAuthenticationPassword;

            if (password != null)
            {
                RestfulClient.DefaultRequestHeaders.Add(
                    LocalAuthenticationMiddleware.PasswordHeaderKey,
                    password
                    );
            }
        }
コード例 #17
0
ファイル: TodayPage.xaml.cs プロジェクト: gitabtion/today_wpf
        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();
            }
        }
コード例 #18
0
        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);
        }
コード例 #19
0
ファイル: TodayPage.xaml.cs プロジェクト: gitabtion/today_wpf
        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();
            }
        }
コード例 #20
0
        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"));
            }
        }
コード例 #21
0
        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);
        }
コード例 #22
0
        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("+"));
        }
コード例 #23
0
ファイル: RestfulClientTests.cs プロジェクト: TianyuanC/dals
 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>>>());
 }
コード例 #24
0
 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 = "未订阅";
     }
 }
コード例 #25
0
        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]));
                }
            }
        }
コード例 #26
0
        /// <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);
            }
        }
コード例 #27
0
        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());
        }
コード例 #28
0
        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);
        }
コード例 #29
0
        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();
            }
        }
コード例 #30
0
        /// <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);
        }
コード例 #31
0
ファイル: Processor.cs プロジェクト: sanlonezhang/ql
        /// <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);
        }