private async void loginButton_Click(object sender, RoutedEventArgs e)
        {
            var client = new WebApiClient();
            try
            {
                var res = await client.LoginAsync(userNameTextBox.Text, passwordTextBox.Password);
                if (res.UserName == "")
                    return;
                
            }
            catch (Exception ex)
            {

            }
            //using (var httpClient = new HttpClient())
            //{
            //    httpClient.DefaultRequestHeaders.Add("ContentType", "application/x-www-form-urlencoded");


            //    var loginModel = new LoginModel()
            //    {
            //        UserName = userNameTextBox.Text,
            //        Password = passwordTextBox.Password
            //    };


            //    var content = new StringContent(loginModel.ToString());
            //    var response = await httpClient.PostAsync(App.ApiToken, content);

            //    MessageDialog dialog;
            //    IUICommand buttonClicked;
            //    string error = "";

            //    if (response.IsSuccessStatusCode)
            //    {


            //        var jsonD = new DataContractJsonSerializer(typeof(TokenModel));

            //        var resultContent = await response.Content.ReadAsByteArrayAsync();
            //        using (var innerStream = new MemoryStream(resultContent))
            //        {
            //            var token = jsonD.ReadObject(innerStream) as TokenModel;
            //            App.Token = token;
            //            return;
            //        }

            //    }
            //    error = await response.Content.ReadAsStringAsync();


            //    dialog = new MessageDialog("Error:\r\n" + error);
            //    dialog.Commands.Add(new UICommand("Ok"));
            //    buttonClicked = await dialog.ShowAsync();

            //}
        }
Пример #2
0
 private void BackgroundThread()
 {
     for (;;)
     {
         var client = new WebApiClient(ConfigurationManager.AppSettings["WebApiAddress"]);
         if (_event.WaitOne(TimeSpan.FromSeconds(Interval)))
             return;
         client.NotifyCaseWorkersAboutClosingCases("arb1234567890system");
     }
 }
Пример #3
0
        static void Main(string[] args)
        {
            var client = new WebApiClient("https://api.github.com").Build<IGitHub>();
            var result = client.RateLimit();
            var json = client.RateLimitJson();

            Console.WriteLine(result);
            Console.WriteLine(json);

            Console.ReadKey();
        }
 public async void Init(int userId, string apiBaseUrl) {
     _userId = userId;
     _apiBaseUrl = apiBaseUrl;
     List<Question> tempQuestions = null;
     using (var apiClient = new WebApiClient(_apiBaseUrl)) {
         tempQuestions = await apiClient.GetAsync<List<Question>>("Questions");
     }
     if (tempQuestions != null && tempQuestions.Count > 0) {
         Questions = tempQuestions;
     }
 }
Пример #5
0
		public void blank_apikeys_config_setting_should_disable_rest_api()
		{
			// Arrange
			RemoveApiKeys();
			WebApiClient apiclient = new WebApiClient();

			// Act
			WebApiResponse response = apiclient.Get("User");

			// Assert
			Assert.That(response.HttpStatusCode, Is.EqualTo(HttpStatusCode.NotFound), response);
		}
Пример #6
0
		public void wrong_apikey_in_header_should_return_401_unauthorized()
		{
			// Arrange
			WebApiClient apiclient = new WebApiClient();
			apiclient.ApiKey = "bad api key";

			// Act
			WebApiResponse response = apiclient.Get("User");

			// Assert
			Assert.That(response.HttpStatusCode, Is.EqualTo(HttpStatusCode.Unauthorized), response);
		}
Пример #7
0
		public void missing_apikey_in_header_should_return_400_badrequest()
		{
			// Arrange
			WebApiClient apiclient = new WebApiClient();
			apiclient.ApiKey = "";

			// Act
			WebApiResponse response = apiclient.Get("User");

			// Assert
			Assert.That(response.HttpStatusCode, Is.EqualTo(HttpStatusCode.BadRequest), response);
		}
Пример #8
0
		public void getusers_should_return_all_users()
		{
			// Arrange
			WebApiClient apiclient = new WebApiClient();

			// Act
			WebApiResponse<List<UserViewModel>> response = apiclient.Get<List<UserViewModel>>("User");

			// Assert
			List<UserViewModel> results = response.Result;
			Assert.That(results.Count(), Is.EqualTo(2), response);
		}
        private async void button_Click(object sender, RoutedEventArgs e)
        {
            var client = new WebApiClient();
            try
            {
                var res = await client.LoginAsync(userNameTextBox.Text, passwordTextBox.Password);
                if (res.UserName == "")
                    return;
            }
            catch(Exception ex)
            {

            }
        }
Пример #10
0
		public void get_should_return_all_pages()
		{
			// Arrange
			AddPage("test", "this is page 1");
			AddPage("page 2", "this is page 2");

			WebApiClient apiclient = new WebApiClient();

			// Act
			WebApiResponse<List<PageViewModel>> response = apiclient.Get<List<PageViewModel>>("Pages");

			// Assert
			IEnumerable<PageViewModel> pages = response.Result;
			Assert.That(pages.Count(), Is.EqualTo(2), response);
		}
Пример #11
0
		public void put_should_update_page()
		{
			// Arrange
			PageContent pageContent = AddPage("test", "this is page 1");
			PageViewModel viewModel = new PageViewModel(pageContent.Page);
			viewModel.Title = "New title";
			
			WebApiClient apiclient = new WebApiClient();

			// Act
			WebApiResponse response = apiclient.Put<PageViewModel>("Pages/Put", viewModel);

			// Assert
			IPageRepository repository = GetRepository();
			Page page = repository.AllPages().FirstOrDefault();
			Assert.That(page.Title, Is.EqualTo("New title"), response);
		}
Пример #12
0
		public void getuser_should_return_admin_user()
		{
			// Arrange
			var queryString = new Dictionary<string, string>()
			{ 
				{ "Id", ADMIN_ID.ToString() }
			};

			WebApiClient apiclient = new WebApiClient();

			// Act
			WebApiResponse<UserViewModel> response = apiclient.Get<UserViewModel>("User", queryString);

			// Assert
			UserViewModel userViewModel = response.Result;
			Assert.That(userViewModel, Is.Not.Null, response);
			Assert.That(userViewModel.Id, Is.EqualTo(ADMIN_ID), response);
		}
Пример #13
0
        public void Authenticate_Should_Return_True_For_Known_User()
        {
            // Arrange
            UserController.UserInfo info = new UserController.UserInfo()
            {
                Email = ADMIN_EMAIL,
                Password = ADMIN_PASSWORD
            };

            WebApiClient apiclient = new WebApiClient();
            apiclient.Login();

            // Act
            WebApiResponse response = apiclient.Post<UserController.UserInfo>("Authenticate", info);

            // Assert
            Assert.That(response.Content, Is.EqualTo("true"), response);
        }
Пример #14
0
		public void get_with_id_should_return_correct_page()
		{
			// Arrange
			PageContent expectedPage = AddPage("test", "this is page 1");
			var queryString = new Dictionary<string, string>()
			{ 
				{ "Id", expectedPage.Page.Id.ToString() }
			};
			WebApiClient apiclient = new WebApiClient();

			// Act
			WebApiResponse<PageViewModel> response = apiclient.Get<PageViewModel>("Pages", queryString);

			// Assert
			PageViewModel actualPage = response.Result;
			Assert.That(actualPage, Is.Not.Null, response.ToString());
			Assert.That(actualPage.Id, Is.EqualTo(expectedPage.Page.Id), response.ToString());
		}
Пример #15
0
        public void SetUp()
        {
            //Due to bug in self hosting scenario and in-memory hosting we need to load the type into memory
            Type type = typeof (TripsController);
            var config = new HttpConfiguration();
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
                );
            config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;
            _server = new HttpServer(config);
            BootstrapWindsorContainer();
            Database.SetInitializer(new TripContextInitializerForTests());
            SetResolver(config);

            client = new WebApiClient(Constants.BaseUri + "api/trips/").AgainstInMemoryServer(_server);
        }
Пример #16
0
        public async Task TestCookieNotFound()
        {
            int id = 9999;

            using (WebApiClient <Restaurant> client = new WebApiClient <Restaurant>(options))
            {
                client.AddCookie(new Cookie("restaurantId", id.ToString(), "/", "localhost"));

                try
                {
                    var rest = await client.GetOneAsync("getUsingCookie");
                }
                catch (WebApiClientException e)
                {
                    Assert.AreEqual(HttpStatusCode.NotFound, e.StatusCode);
                    Assert.IsNotNull(e.Details);
                    Assert.AreEqual("Restaurant not found", e.Details.Message);
                }
            }
        }
Пример #17
0
        public async Task TestCookieUsingExplicitHeader()
        {
            int id = 1;

            var handler = new HttpClientHandler()
            {
                UseCookies = false
            };

            using (WebApiClient <Restaurant> client = new WebApiClient <Restaurant>(options, handler))
            {
                client.Headers.Add("Cookie", "restaurantId=" + id);

                var rest = await client.GetOneAsync("getUsingCookie");

                //assert
                Assert.IsNotNull(rest);
                Assert.AreEqual(id, rest.Id);
            }
        }
Пример #18
0
        public void search_should_return_result_based_on_query()
        {
            // Arrange
            AddPage("test", "this is page 1");
            AddPage("page 2", "this is page 2");
            var queryString = new Dictionary<string, string>()
            {
                { "query", "test" }
            };

            WebApiClient apiclient = new WebApiClient();

            // Act
            apiclient.Get("Search/CreateIndex");
            WebApiResponse<List<PageViewModel>> response = apiclient.Get<List<PageViewModel>>("Search", queryString);

            // Assert
            IEnumerable<PageViewModel> pages = response.Result;
            Assert.That(pages.Count(), Is.EqualTo(1), response);
        }
Пример #19
0
        public BusSearchResult GetBusDetails(string from, string to, string dateOfJourney)
        {
            BusSearchResult bussesAvailable = new BusSearchResult();
            var             url             = BusinessConstants.GoibiboBusSearchApi;

            url = string.Format(url, from, to, dateOfJourney);
            url = AddAuthentication(url);
            var serviceAgent = new WebApiClient(apiUri, appId, appSecret);

            using (var response = serviceAgent.GetAsync(url))
            {
                var result = response.Result;
                if (result.IsSuccessStatusCode)
                {
                    var jsonResponse = result.Content.ReadAsStringAsync().Result;
                    bussesAvailable = JsonConvert.DeserializeObject <BusSearchResult>(jsonResponse);
                }
            }
            return(bussesAvailable);
        }
Пример #20
0
        public ActionResult ApplicationDetails(FormCollection collection)
        {
            Bill toAdd = BillGenerator.GenerateBill(collection);

            using (HttpClient client = WebApiClient.InitializeClient(Request.Url.Scheme + "://" + Request.Url.Authority + Request.ApplicationPath.TrimEnd('/') + "/"))
            {
                JsonMediaTypeFormatter formatter = new JsonMediaTypeFormatter();

                formatter.SerializerSettings.TypeNameHandling = TypeNameHandling.All;

                HttpResponseMessage response = client.PostAsync("api/Bill", toAdd, formatter).Result;

                if (response.IsSuccessStatusCode)
                {
                    return(RedirectToAction("ApplicationDetails", "Service", new { id = toAdd.ApplicationId }));
                }
            }

            return(RedirectToAction("Index"));
        }
Пример #21
0
        private void LoadTestInfo_Click(object sender, RoutedEventArgs e)
        {
            string        path = AppDomain.CurrentDomain.BaseDirectory + "Data\\Test";
            DirectoryInfo dir  = new DirectoryInfo(path);

            FileInfo[] files = dir.GetFiles();

            string host = ConfigurationManager.AppSettings["TargetHost"];
            string port = ConfigurationManager.AppSettings["Port2"];

            foreach (FileInfo file in files)
            {
                string content = File.ReadAllText(file.FullName);
                //CameraAlarmInfo info = JsonConvert.DeserializeObject<CameraAlarmInfo>(content);
                //info.ParseData();
                WebApiClient client2 = new WebApiClient(host, port);
                string       result2 = client2.PostEntity <string>("listener/ExtremeVision/callback/", content, true);
                //MessageBox.Show("result2:" + result2);
            }
        }
Пример #22
0
        public void UpdateFromWebApiTest()
        {
            var trans = ContextFactory.GetDBContext().OWTQ_TransferRequest.Include("WTQ1_TransferRequestDetails")
                        .FirstOrDefault(t => t.IdTransferRequestL == 13);

            var db = ContextFactory.GetDBContext();

            var transfer = WebApiClient.GetTransferRequest("144").Result;

            trans.UpdateModelPropertiesFrom(transfer);

            db.SaveChanges();


            //var details = db.WTQ1_TransferRequestDetails.Where(t => t.IdTransferRequestL == 13).ToList();

            //details.UpdateModelPropertiesFrom(trans.WTQ1_TransferRequestDetails);

            //db.SaveChanges();
        }
Пример #23
0
        /// <summary>
        /// The update user view.
        /// </summary>
        /// <param name="userId">the user id to update.</param>
        /// <returns>updating view</returns>
        public async Task <ActionResult> GetUpdateUser(int userId)
        {
            ManageUserFormData userFormData = new ManageUserFormData();
            UserRequestData    findRequest  = new UserRequestData()
            {
                UserDto = new UserItemData {
                    UserId = userId
                },
                FindUserDto = FindUserItemData.UserId
            };

            UserResultData result = await WebApiClient.PostFormJsonAsync <UserRequestData, UserResultData>(Constant.WebApiControllerUser, Constant.WebApiFindUser, findRequest);

            if (result != null && result.OperationSuccess && result.UserDto != null)
            {
                userFormData = result.ToUserFormData();
            }

            ViewBag.action = "UpdateUser";
            return(PartialView("Partials/_ManageUser", userFormData));
        }
Пример #24
0
        public void TestGetPossibleTimes_FirstPojectionNotOK()
        {
            //TestData
            var testData =
                "{\"ScheduleResult\":{\"Schedules\":[{\"ContractTimeMinutes\":480,\"Date\":\"\\/Date(1450051200000+0000)\\/\",\"IsFullDayAbsence\":false,\"Name\":\"Daniel Billsus\",\"PersonId\":\"4fd900ad-2b33-469c-87ac-9b5e015b2564\",\"Projection\":[{\"Color\":\"#FFFF00\",\"Description\":\"Lunch\",\"Start\":\"\\/Date(1450094400000+0000)\\/\",\"minutes\":60},{\"Color\":\"#1E90FF\",\"Description\":\"Ok\",\"Start\":\"\\/Date(1450098000000+0000)\\/\",\"minutes\":120},{\"Color\":\"#FF0000\",\"Description\":\"Ok\",\"Start\":\"\\/Date(1450105200000+0000)\\/\",\"minutes\":15}]}]}}";
            var dataObj          = JObject.Parse(testData);
            var scheduleresponse = dataObj;
            //var scheduleresponse = new scheduleresponse(dataObj); // need to create a constructor in the  scheduleresponse class

            // PreAssert testData: first Projection Not Ok = Lunch
            //Assert.AreEqual("Lunch", ScheduleResponse.ScheduleResult.Schedules[0].Projection[0].Description);

            //Test
            var result = WebApiClient.GetPossibleTimes(scheduleresponse);

            //Assert
            Assert.AreEqual(DateTimeOffset.Parse("2015-12-14 14:00:00", CultureInfo.InvariantCulture), result.Item2.First().First());
            Assert.AreEqual(DateTimeOffset.Parse("2015-12-14 16:00:00", CultureInfo.InvariantCulture), result.Item2.First().Last());
            Assert.AreEqual(9, result.Item2.First().Count);
            //Assert.Pass();
        }
Пример #25
0
        public async Task TestCookieGetFeedbackUsingImplicitHeader()
        {
            int id      = 1;
            var handler = new HttpClientHandler()
            {
                UseCookies = false
            };

            using (WebApiClient <Restaurant> client = new WebApiClient <Restaurant>(options, handler))
            {
                client.AddCookie(new Cookie("restaurantId", id.ToString(), "/", "localhost"));

                var rest = await client.GetOneAsync("getUsingCookie");

                Assert.IsNotNull(rest);
                Assert.AreEqual(id, rest.Id);

                var col = handler.CookieContainer.GetCookies(new Uri(this.options.BaseAddress));
                Assert.IsEmpty(col, "It is not possible to get cookies when not using CookieContainer");
            }
        }
Пример #26
0
        public async Task TestBearerAuthGetAllSameToken()
        {
            //arrange
            options.Authentication = new BearerTokenAuthentication(userName, password, this.tokenUri);

            using (WebApiClient <Restaurant> client = new WebApiClient <Restaurant>(options))
            {
                //act
                List <Restaurant> restaurants = await client.GetManyAsync("GetWithAuth");

                Assert.IsNotEmpty(restaurants);

                var auth = options.Authentication as BearerTokenAuthentication;
                Assert.IsTrue(auth.HasToken);
                Assert.IsNotNullOrEmpty(auth.Token);

                restaurants = await client.GetManyAsync("Get");

                Assert.IsNotEmpty(restaurants);
            }
        }
Пример #27
0
        public async Task TestBearerAuthGetAllInvalidTokenUri()
        {
            //arrange
            options.Authentication = new BearerTokenAuthentication(userName, password, "http://localhost/api/invalidTokenUri");

            using (WebApiClient <Restaurant> client = new WebApiClient <Restaurant>(options))
            {
                try
                {
                    //act
                    List <Restaurant> restaurants = await client.GetManyAsync("GetWithAuth");

                    Assert.Fail("Expected ServiceUnavailable exception");
                }
                catch (WebApiClientException e)
                {
                    //assert
                    Assert.AreEqual(HttpStatusCode.ServiceUnavailable, e.StatusCode);
                }
            }
        }
Пример #28
0
        public async Task TestBearerAuthGetAllUnauthorized()
        {
            //arrange
            options.Authentication = new BearerTokenAuthentication("xxx", "yyy", this.tokenUri);

            using (WebApiClient <Restaurant> client = new WebApiClient <Restaurant>(options))
            {
                try
                {
                    //act
                    List <Restaurant> restaurants = await client.GetManyAsync("GetWithAuth");

                    Assert.Fail("Expected Unauthorized exception");
                }
                catch (WebApiClientException e)
                {
                    //assert
                    Assert.AreEqual(HttpStatusCode.Unauthorized, e.StatusCode);
                }
            }
        }
Пример #29
0
        public async Task <ActionResult> MyTinyUrl(string id)
        {
            RequestCarrier req = new RequestCarrier()
            {
                PayLoad = id
            };
            WebApiClient        wClient         = new WebApiClient();
            HttpResponseMessage responseMessage = await wClient.PostAsyncMyTinyURL(req);

            if (responseMessage.IsSuccessStatusCode)
            {
                var responseData = responseMessage.Content.ReadAsStringAsync().Result;
                var data         = JsonConvert.DeserializeObject <ResponseCarrier>(responseData);
                if (data != null && data.PayLoad != null)
                {
                    string redirectUrl = data.PayLoad.ToString();
                    return(Redirect(redirectUrl));
                }
            }
            return(RedirectToAction("Index", "Home"));
        }
Пример #30
0
        public string GetServiceConsultants(int service_id)
        {
            List <ServiceConsultant> consultants = new List <ServiceConsultant>();

            using (HttpClient client = WebApiClient.InitializeClient(Request.Url.Scheme + "://" + Request.Url.Authority + Request.ApplicationPath.TrimEnd('/') + "/"))
            {
                HttpResponseMessage message = client.GetAsync("api/ServiceConsultants/GetServiceConsultants?service_id=" + service_id.ToString()).Result;

                if (message.IsSuccessStatusCode)
                {
                    consultants = message.Content.ReadAsAsync <List <ServiceConsultant> >().Result;
                }
            }

            if (consultants.Count() == 0)
            {
                consultants = null;
            }

            return(JsonConvert.SerializeObject(consultants));
        }
Пример #31
0
        private async void TryLoginAsync(object arg)
        {
            var client = new WebApiClient();

            var response = await client.LoginAsync(new LoginDto
            {
                Login    = Username,
                Password = Password
            });

            if (response != null && response.Code == 200)
            {
                MainWindow window = new MainWindow(response.Data.Token);
                window.Show();
                (arg as Window).Close();
            }
            else
            {
                MessageBox.Show("Błędny login lub hasło.\r\nSpróbuj ponownie.", "Błędne dane");
            }
        }
Пример #32
0
        /// <summary>
        /// The update rule view.
        /// </summary>
        /// <param name="ruleId">the rule id to update.</param>
        /// <returns>updating view</returns>
        public async Task <ActionResult> GetUpdateRule(int ruleId)
        {
            ManageRuleFormData ruleFormData = new ManageRuleFormData();
            RuleRequestData    findRequest  = new RuleRequestData
            {
                RuleDto = new RuleItemData
                {
                    RuleId = ruleId
                },
                FindRuleItemData = FindRuleItemData.RuleId
            };

            RuleResultData result = await WebApiClient.PostFormJsonAsync <RuleRequestData, RuleResultData>(Constant.WebApiControllerRule, Constant.WebApiFindRules, findRequest);

            if (result != null && result.OperationSuccess && result.RuleDto != null)
            {
                ruleFormData = result.ToFormData();
            }
            ViewBag.action = "UpdateRule";
            return(PartialView("Partials/_ManageRule", ruleFormData));
        }
        public async Task TestDefaultAuthGetAllUnauthorized()
        {
            //arrange
            options.Authentication = new WindowsIntegratedAuthentication("xxx", "yyy");

            using (WebApiClient <Restaurant> client = new WebApiClient <Restaurant>(options))
            {
                try
                {
                    //act
                    var restaurants = await client.GetManyAsync("GetWithAuth");

                    Assert.Fail("Expected Unauthorized exception");
                }
                catch (WebApiClientException e)
                {
                    //assert
                    Assert.AreEqual(HttpStatusCode.Unauthorized, e.StatusCode);
                }
            }
        }
Пример #34
0
        private static void LoginIfNeccesary(WebApiClient ApiClient)
        {
            if (CurrentApiToken == null || ApiTokenExpiry < DateTime.Now.AddMinutes(-2))
            {
                string      errorMessage = "";
                Parameter[] paramList    = new Parameter[2];
                paramList[0] = new Parameter("leagueKey", "ABC123", ParameterType.QueryString);
                paramList[1] = new Parameter("hashedPassword", "2AC9CB7DC02B3C0083EB70898E549B63", ParameterType.QueryString);

                var loginResponse = ApiClient.Get <LoginResponse>("Login", paramList, ref errorMessage);
                if (loginResponse != null)
                {
                    CurrentApiToken = loginResponse.Login.LoginKey;
                    ApiTokenExpiry  = loginResponse.Login.Expiry;
                    League          = new League()
                    {
                        LeagueId = loginResponse.LeagueId, LeagueName = loginResponse.LeagueName, Logo = loginResponse.Logo
                    };
                }
            }
        }
Пример #35
0
        /// <summary>
        /// The update subscriber view.
        /// </summary>
        /// <param name="subscriberId">the subscriber id to update.</param>
        /// <returns>updating view</returns>
        public async Task <ActionResult> GetUpdateSubscriber(int subscriberId)
        {
            SubscriberFormData    subscriberFormData = new SubscriberFormData();
            SubscriberRequestData findRequest        = new SubscriberRequestData
            {
                SubscriberDto = new SubscriberItemData
                {
                    SubscriberId = subscriberId
                },
                FindSubscriberDto = FindSubscriberItemData.SubscriberId
            };

            SubscriberResultData result = await WebApiClient.PostFormJsonAsync <SubscriberRequestData, SubscriberResultData>(Constant.WebApiControllerNewsletters, Constant.WebApiFindSubscribers, findRequest);

            if (result != null && result.OperationSuccess && result.SubscriberDto != null)
            {
                subscriberFormData = result.ToFormData();
            }
            ViewBag.Action = "UpdateSubscriber";
            return(PartialView("Partials/_ManageSubscriber", subscriberFormData));
        }
        public async Task TestDefaultCredentialsAuthGetAllUnauthorized()
        {
            using (WebApiClient <Restaurant> client = new WebApiClient <Restaurant>(options, new HttpClientHandler()
            {
                UseDefaultCredentials = false
            }))
            {
                try
                {
                    //act
                    var restaurants = await client.GetManyAsync("GetWithAuth");

                    Assert.Fail("Expected Unauthorized exception");
                }
                catch (WebApiClientException e)
                {
                    //assert
                    Assert.AreEqual(HttpStatusCode.Unauthorized, e.StatusCode);
                }
            }
        }
Пример #37
0
        public void WebAPIClient_WrongAPIKey()
        {
            string apiKey  = "gysefsdfbjh";
            string baseURI = "http://www.omdbapi.com";
            string url     = "?t=thor ragnarok";

            IWebApiClient client = new WebApiClient();

            try
            {
                var movie = client.GetAsync <Movie>(baseURI, url, apiKey).Result;
                Console.WriteLine(JsonConvert.SerializeObject(movie));
            }
            catch (Exception ex)
            {
                if (ex.Message != "One or more errors occurred. (You are not allowed to use this service.)")
                {
                    throw ex;
                }
            }
        }
Пример #38
0
        /// <summary>
        /// Get News Model for Update
        /// </summary>
        /// <param name="newsId"></param>
        /// <returns></returns>
        public async Task <ActionResult> GetUpdateNews(int?newsId)
        {
            NewsFormData newsFormData = new NewsFormData
            {
                TranslationsList = new List <NewsTranslationFormData>()
            };

            if (newsId.HasValue)
            {
                NewsRequestData findNewsRequest = new NewsRequestData
                {
                    NewsDto = new NewsItemData {
                        NewsId = newsId.Value
                    },
                    FindNewsDto = FindNewsItemData.NewsId
                };
                NewsResultData resultNews = await WebApiClient.PostFormJsonAsync <NewsRequestData, NewsResultData>(Constant.WebApiControllerNews, Constant.WebApiFindNews, findNewsRequest);

                if (resultNews != null && resultNews.OperationSuccess && resultNews.NewsDto != null)
                {
                    newsFormData.NewsId   = resultNews.NewsDto.NewsId;
                    newsFormData.NewsDate = resultNews.NewsDto.NewsDate.ToString("dd/MM/yyyy");
                    NewsTranslationRequestData findNewsTranslationRequest = new NewsTranslationRequestData()
                    {
                        NewsTranslationDto = new NewsTranslationItemData {
                            NewsId = newsId.Value
                        },
                        FindNewsTranslationDto = FindNewsTranslationItemData.NewsId
                    };
                    NewsTranslationResultData resultNewsTranslation = await WebApiClient.PostFormJsonAsync <NewsTranslationRequestData, NewsTranslationResultData>(Constant.WebApiControllerNews, Constant.WebApiFindNewsTranslations, findNewsTranslationRequest);

                    if (resultNewsTranslation != null && resultNewsTranslation.OperationSuccess && resultNewsTranslation.NewsTranslationDtoList != null)
                    {
                        newsFormData.TranslationsList = resultNewsTranslation.NewsTranslationDtoList.ToFormDataList();
                    }
                }
            }
            ViewBag.Action = "UpdateNews";
            return(PartialView("Partials/_ManageNews", newsFormData));
        }
Пример #39
0
        /// <summary>
        /// Get NewsletterMail Model for Update
        /// </summary>
        /// <param name="newsletterMailId"></param>
        /// <returns></returns>
        public async Task <ActionResult> GetUpdateNewsletterMail(int?newsletterMailId)
        {
            NewsletterMailFormData newsletterMailFormData = new NewsletterMailFormData
            {
                TranslationsList = new List <NewsletterMailTranslationFormData>()
            };

            if (newsletterMailId.HasValue)
            {
                NewsletterMailRequestData findNewsletterMailRequest = new NewsletterMailRequestData
                {
                    NewsletterMailDto = new NewsletterMailItemData {
                        NewsletterMailId = newsletterMailId.Value
                    },
                    FindNewsletterMailDto = FindNewsletterMailItemData.NewsletterMailId
                };
                NewsletterMailResultData resultNewsletterMail = await WebApiClient.PostFormJsonAsync <NewsletterMailRequestData, NewsletterMailResultData>(Constant.WebApiControllerNewsletters, Constant.WebApiFindNewsletterMails, findNewsletterMailRequest);

                if (resultNewsletterMail != null && resultNewsletterMail.OperationSuccess && resultNewsletterMail.NewsletterMailDto != null)
                {
                    newsletterMailFormData.NewsletterMailId = resultNewsletterMail.NewsletterMailDto.NewsletterMailId;

                    NewsletterMailTranslationRequestData findNewsletterMailTranslationRequest = new NewsletterMailTranslationRequestData()
                    {
                        NewsletterMailTranslationDto = new NewsletterMailTranslationItemData {
                            NewsletterMailId = newsletterMailId.Value
                        },
                        FindNewsletterMailTranslationDto = FindNewsletterMailTranslationItemData.NewsletterMailId
                    };
                    NewsletterMailTranslationResultData resultNewsletterMailTranslation = await WebApiClient.PostFormJsonAsync <NewsletterMailTranslationRequestData, NewsletterMailTranslationResultData>(Constant.WebApiControllerNewsletters, Constant.WebApiFindNewsletterMailTranslations, findNewsletterMailTranslationRequest);

                    if (resultNewsletterMailTranslation != null && resultNewsletterMailTranslation.OperationSuccess && resultNewsletterMailTranslation.NewsletterMailTranslationDtoList != null)
                    {
                        newsletterMailFormData.TranslationsList = resultNewsletterMailTranslation.NewsletterMailTranslationDtoList.ToFormDataList();
                    }
                }
            }
            ViewBag.Action = "UpdateNewsletterMail";
            return(PartialView("Partials/_ManageNewsletterMail", newsletterMailFormData));
        }
Пример #40
0
        private static GameScore GetGameScore(int gameId)
        {
            SetTimeoutsFromSave();
            var ApiClient = new WebApiClient(BaseWebApiAddress);

            LoginIfNeccesary(ApiClient);

            string errorMsg = "";

            Parameter[] paramList = new Parameter[2];
            paramList[0] = new Parameter("apiToken", Connector.CurrentApiToken, ParameterType.QueryString);
            paramList[1] = new Parameter("gameId", gameId, ParameterType.QueryString);

            var score = ApiClient.Get <GameScoreResponse>("Scoring/Score", paramList, ref errorMsg);

            Parameter[] paramList2 = new Parameter[2];
            paramList2[0] = new Parameter("apiToken", Connector.CurrentApiToken, ParameterType.QueryString);
            paramList2[1] = new Parameter("gameId", gameId, ParameterType.QueryString);

            var fouls = ApiClient.Get <GameFoulsResponse>("Scoring/Fouls", paramList, ref errorMsg);

            var homeTeamTimeouts = string.IsNullOrEmpty(_homeTeamTimeoutsRemaining) ? 5 : Convert.ToInt32(_homeTeamTimeoutsRemaining);
            var awayTeamTimeouts = string.IsNullOrEmpty(_awayTeamTimeoutsRemaining) ? 5 : Convert.ToInt32(_awayTeamTimeoutsRemaining);

            if (score != null && fouls != null)
            {
                return(new GameScore()
                {
                    HomeTeamFouls = fouls.HomeTeamFouls,
                    AwayTeamFouls = fouls.AwayTeamFouls,
                    HomeTeamScore = score.HomeTeamScore,
                    AwayTeamScore = score.AwayTeamScore,
                    HomeTeamTimeoutsRemaining = homeTeamTimeouts,
                    AwayTeamTimeoutsRemaining = awayTeamTimeouts
                });
            }

            return(null);
        }
Пример #41
0
        /// <summary>
        /// Get newsletterMail form to create.
        /// </summary>
        /// <returns></returns>
        public async Task <ActionResult> GetCreateNewsletterMail()
        {
            NewsletterMailFormData newsletterMailFormData = new NewsletterMailFormData {
                TranslationsList = new List <NewsletterMailTranslationFormData>()
            };
            LanguageResultData result = await WebApiClient.GetAsync <LanguageResultData>(Constant.WebApiControllerLanguages, Constant.WebApiLanguageList);

            if (result != null && result.OperationSuccess && result.LanguageDtoList != null)
            {
                foreach (var language in result.LanguageDtoList)
                {
                    var translation = new NewsletterMailTranslationFormData
                    {
                        LanguagePrefix = language.LanguagePrefix,
                        LanguageId     = language.LanguageId,
                    };
                    newsletterMailFormData.TranslationsList.Add(translation);
                }
            }
            ViewBag.Action = "CreateNewsletterMail";
            return(PartialView("Partials/_ManageNewsletterMail", newsletterMailFormData));
        }
Пример #42
0
        public void CreateTest()
        {
            var payment = new Payment();

            payment.PayWay            = PayWays.Alipay;
            payment.TradeMode         = TradeMode.Payout;
            payment.BizSource         = PaymentSources.OpenEnterpriseService;
            payment.CommodityQuantity = 1;
            payment.TotalFee          = 0.01M;
            payment.CommoditySubject  = string.Format("购买服务 ¥{0}", payment.TotalFee);
            payment.BuyerId           = payment.OwnerId;

            var responseResult = WebApiClient.HttpPost(ApiEnvironment.Payment_CreateTrade_Endpoint, payment);

            Assert.AreEqual(HttpStatusCode.OK, responseResult.StatusCode);
            Assert.IsNotNullOrEmpty(responseResult.Content);

            var result = WebCore.JsonExtension.ConvertEntity <PaymentResult>(responseResult.Content);

            Assert.IsTrue(result.Success);
            Console.WriteLine(responseResult.Content);
        }
Пример #43
0
        public void ApplyAuthenticationTest()
        {
            var entity = new OrganizationProfile();

            entity.Identity             = TestHelper.GetRndString();
            entity.AuthenticationImages = new string[TestHelper.GetRndNumber(1, 4)];
            for (var i = 0; i < entity.AuthenticationImages.Length; i++)
            {
                entity.AuthenticationImages[i] = TestHelper.GetTestImageStream();
            }

            var responseResult = WebApiClient.HttpPost(ApiEnvironment.Consultant_ApplyAuthentication_Endpoint, entity);

            Assert.AreEqual(HttpStatusCode.OK, responseResult.StatusCode);
            Assert.IsNotNullOrEmpty(responseResult.Content);

            var images = responseResult.Content.ConvertEntity <string[]>();

            Assert.IsNotNull(images);

            Assert.AreEqual(images.Length, entity.AuthenticationImages.Length);
        }
Пример #44
0
		public void post_should_add_page()
		{
			// Arrange
			PageViewModel page = new PageViewModel()
			{
				Title = "Hello",
				CreatedBy = "admin",
				CreatedOn = DateTime.UtcNow,
				Content = "some content",
				RawTags = "tag1,tag2"
			};

			WebApiClient apiclient = new WebApiClient();

			// Act
			WebApiResponse response = apiclient.Post<PageViewModel>("Pages", page);

			// Assert
			IPageRepository repository = GetRepository();
			IEnumerable<Page> pages = repository.AllPages();
			Assert.That(pages.Count(), Is.EqualTo(1), response);
		}
Пример #45
0
        /// <summary>
        /// Get Theme Translations
        /// </summary>
        /// <param name="themeId"></param>
        /// <returns></returns>
        private async Task <List <ThemeTranslationItemData> > GetThemeTranslations(int?themeId)
        {
            List <ThemeTranslationItemData> translationsList            = new List <ThemeTranslationItemData>();
            ThemeTranslationRequestData     findThemeTranslationRequest = new ThemeTranslationRequestData()
            {
                ThemeTranslationDto = new ThemeTranslationItemData {
                    ThemeId = themeId
                },
                FindThemeTranslationDto = FindThemeTranslationItemData.ThemeId
            };
            ThemeTranslationResultData resultThemeTranslation =
                await WebApiClient.PostFormJsonAsync <ThemeTranslationRequestData, ThemeTranslationResultData>(
                    Constant.WebApiControllerRessources, Constant.WebApiFindThemeTranslations, findThemeTranslationRequest);

            if (resultThemeTranslation != null && resultThemeTranslation.OperationSuccess &&
                resultThemeTranslation.ThemeTranslationDtoList != null)
            {
                translationsList.AddRange(resultThemeTranslation.ThemeTranslationDtoList.Where(n => n.LanguageId == _lang)
                                          .ToList());
            }
            return(translationsList);
        }
Пример #46
0
        public App()
        {
            InitializeComponent();

            MainPage = new SignInView();

            _navigator = new NavigationService(this, new ViewLocator());

            Application.Current.Properties["ApiUrl"] = "http://192.168.42.151:5000/";


            if (WebApiClient.Validate())
            {
                _navigator.PresentAsNavigatableMainPage(new MainPageViewModel(_navigator));
            }
            else
            {
                _navigator.PresentAsNavigatableMainPage(new SignInViewModel(_navigator));
            }

            //_navigator.PresentAsNavigatableMainPage(new TeamsViewModel(_navigator));
        }
        private async void DoSaveAnswers() {
            var answers = new List<UserAnswer>();
            foreach (var answer in _questions.Select(q =>
                new { q.QuestionId, AnswerId = FindSelectedAnswer(q.PossibleAnswers) })) {

                if (answer.AnswerId > 0) {
                    answers.Add(new UserAnswer() {
                        UserId = _userId,
                        QuestionId = answer.QuestionId,
                        AnswerId = answer.AnswerId
                    });
                }
            }

            IAlertMessage alertMsg = Mvx.Resolve<IAlertMessage>();
            AlertMessageResult msgResult = AlertMessageResult.Yes;

            if (answers.Count == 0) {
                msgResult = await alertMsg.ShowAsync(
                    "You did not answer any questions. Are you sure you want to continue?",
                    "No Questions Answered",
                    AlertMessageButtons.YesNo);
            }
            else if (answers.Count < _questions.Count) {
                msgResult = await alertMsg.ShowAsync(
                    "You did not answer all of the questions. Are you sure you want to continue?",
                    "Not All Questions Answered",
                    AlertMessageButtons.YesNo);
            }

            if (msgResult == AlertMessageResult.Yes) {
                if (answers.Count > 0) {
                    using (var apiClient = new WebApiClient(_apiBaseUrl)) {
                        await apiClient.PostAsync<List<UserAnswer>>(answers, "UserAnswers");
                    }
                }
                ShowViewModel<DoneViewModel>();
            }
        }
Пример #48
0
        /// <summary>
        /// Get the news translation list.
        /// </summary>
        /// <param name="newsId">the news id.</param>
        /// <returns></returns>
        private async Task <List <NewsTranslationItemData> > GetNewsTranslations(int newsId)
        {
            List <NewsTranslationItemData> translationsList           = new List <NewsTranslationItemData>();
            NewsTranslationRequestData     findNewsTranslationRequest = new NewsTranslationRequestData
            {
                NewsTranslationDto = new NewsTranslationItemData {
                    NewsId = newsId
                },
                FindNewsTranslationDto = FindNewsTranslationItemData.NewsId
            };
            NewsTranslationResultData resultNewsTranslation =
                await WebApiClient.PostFormJsonAsync <NewsTranslationRequestData, NewsTranslationResultData>(
                    Constant.WebApiControllerNews, Constant.WebApiFindNewsTranslations, findNewsTranslationRequest);

            if (resultNewsTranslation != null && resultNewsTranslation.OperationSuccess &&
                resultNewsTranslation.NewsTranslationDtoList != null)
            {
                translationsList.AddRange(resultNewsTranslation.NewsTranslationDtoList.Where(n => n.LanguageId == _lang)
                                          .ToList());
            }
            return(translationsList);
        }
Пример #49
0
        private async void DoLogin() {
            if (_emailAddress.Trim() != "" && _password.Trim() != "") {
                using (var apiClient = new WebApiClient(apiBaseUrl)) {
                    User user = await apiClient.GetAsync<User>("User", _emailAddress, _password);
                    IAlertMessage alertMsg = Mvx.Resolve<IAlertMessage>();

                    if (user != null && user.UserId != 0) {
                        AlertMessageResult msgResult =
                            await alertMsg.ShowAsync(
                            "Welcome back, " + user.FirstName + " " + user.LastName + ".",
                            "Login Successful",
                            AlertMessageButtons.OK);
                        ShowViewModel<QuestionViewModel>(new { userId = user.UserId, apiBaseUrl = this.apiBaseUrl });
                    }
                    else {
                        AlertMessageResult msgResult =
                            await alertMsg.ShowAsync(
                            "Unable to login with this username and password.",
                            "Login Unsuccessful",
                            AlertMessageButtons.OK);
                    }
                }
            }
        }
Пример #50
0
 public MissionService()
 {
     _client = new WebApiClient(Constants.BaseUrl);
 }
Пример #51
0
 public AnnouncementService()
 {
     _client = new WebApiClient(Constants.BaseUrl);
 }
Пример #52
0
        private Task LoginAsync()
        {
            return Task.Factory.StartNew(() =>
            {
                CommandExecuting = true;
                //Try to signin
                WebApiClient client;
                try
                {
                    client = new WebApiClient(@AppUrl, Login, Password);
                }
                catch (Exception exc)
                {
                    MessageBox.Show(exc.Message);
                    return false;
                }

                try
                {
                    //Initialize DataContext with Url and Access token
                    CaffeDataContext.InitializeContext(@AppUrl + @"/CaffeDataService.svc", client.Token);

                }
                catch (Exception exc)
                {
                    MessageBox.Show(exc.Message);
                    return false;
                }

                var userModel = client.GetUserInfo();

                if (userModel.Role == UserRoles.Manager.ToString())
                {
                    _hostPage.Dispatcher.Invoke(() => _hostPage.NavigationService.Navigate(new ManagerMainPage(userModel)));
                }
                if (userModel.Role == UserRoles.Cashier.ToString())
                {
                    _hostPage.Dispatcher.Invoke(() => _hostPage.NavigationService.Navigate(new CashierMainPage(userModel)));
                }
                if (userModel.Role == UserRoles.SuperUser.ToString())
                {
                    _hostPage.Dispatcher.Invoke(() => _hostPage.NavigationService.Navigate(new SuperuserMainPage(userModel)));
                }
                return true;
            }).ContinueWith((result) => CommandExecuting = false);
        }
Пример #53
0
 public NewsService()
 {
     _client = new WebApiClient(Constants.BaseUrl);
 }
Пример #54
0
 public WebClientProxy(Type type, WebApiClient client)
     : base(type)
 {
     _client = client;
 }
 public void Setup()
 {
     Database.Clear();
     DefaultUser.Reset();
     _client = DefaultUser.CreateWebApiClient();
 }
 public void TearDown()
 {
     _client = null;
     Database.Clear();
 }
Пример #57
0
        public void Logout_Should_Remove_Auth_Cookie()
        {
            // Arrange
            WebApiClient apiclient = new WebApiClient();
            apiclient.Login();
            apiclient.Get("Logout");
            apiclient.Get("User");

            // Act
            apiclient.Login();
            apiclient.Get("Logout");
            WebApiResponse response = apiclient.Get("User");

            // Assert
            Assert.That(response.HttpStatusCode, Is.EqualTo(HttpStatusCode.Unauthorized), response);
        }
Пример #58
0
        public static void InitImpl()
        {
            if(BooksApp != null)
            return;
              LogFilePath = ConfigurationManager.AppSettings["LogFilePath"];
              DeleteLocalLogFile();

              var protectedSection = (NameValueCollection)ConfigurationManager.GetSection("protected");
              var loginCryptoKey = protectedSection["LoginInfoCryptoKey"];
              var connString = protectedSection["MsSqlConnectionString"];
              var logConnString = protectedSection["MsSqlLogConnectionString"];

              BooksApp = new BooksEntityApp(loginCryptoKey);
              //Add mock email/sms service
              NotificationListener = new NotificationListener(BooksApp, blockAll: true);
              //Set magic captcha in login settings, so we can pass captcha in unit tests
              var loginStt = BooksApp.GetConfig<Vita.Modules.Login.LoginModuleSettings>();
              loginStt.MagicCaptcha = "Magic";
              BooksApp.Init();
              //connect to database
              var driver = MsSqlDbDriver.Create(connString);
              var dbOptions = MsSqlDbDriver.DefaultMsSqlDbOptions;
              var dbSettings = new DbSettings(driver, dbOptions, connString, upgradeMode: DbUpgradeMode.Always); // schemas);
              var resetDb = ConfigurationManager.AppSettings["ResetDatabase"] == "true";
              if(resetDb)
            Vita.UnitTests.Common.TestUtil.DropSchemaObjects(dbSettings);
              BooksApp.ConnectTo(dbSettings);
              var logDbSettings = new DbSettings(driver, dbOptions, logConnString);
              BooksApp.LoggingApp.ConnectTo(logDbSettings);
              BooksApp.LoggingApp.LogPath = LogFilePath;
              TestUtil.DeleteAllData(BooksApp, exceptEntities: new [] {typeof(IDbInfo), typeof(IDbModuleInfo)});
              TestUtil.DeleteAllData(BooksApp.LoggingApp);

              SampleDataGenerator.CreateUnitTestData(BooksApp);
              var serviceUrl = ConfigurationManager.AppSettings["ServiceUrl"];
              StartService(serviceUrl);
              Client = new WebApiClient(serviceUrl);
              Client.InnerHandler.AllowAutoRedirect = false; //we need it for Redirect test
        }
Пример #59
0
 public GoogleBooksApiClient()
 {
     ApiClient = new WebApiClient(GoogleBooksUrl, ClientOptions.Default | ClientOptions.CamelCaseNames, typeof(GoogleBadRequestResponse));
 }