Example #1
0
        static void Main(string[] args)
        {
            ApiProxy client = new ApiProxy("http://localhost:8600");
            App      app    = new App(client);

            app.RunAsync().Wait();
        }
Example #2
0
        public void Api_Submit_InvalidWeatherRequest_ReturnsNotFound(
            int woeId,
            ApiProxy apiProxy,
            IWeatherRequest weatherRequest,
            IWeatherResponse weatherResponse)
        {
            $"Given a woeId value of {woeId}"
            .x(() => weatherRequest = new WeatherRequest {
                WoeId = woeId
            });

            "And an ApiProxy"
            .x(() => apiProxy = new ApiProxy(_metaWeatherService));

            "When the weather request is submitted"
            .x(
                async() => weatherResponse =
                    await apiProxy.SubmitWeatherRequest(weatherRequest).ConfigureAwait(false));

            "Then the weather response should return StatusCode 404, and Forecasts should be empty"
            .x(
                () =>
            {
                using (new AssertionScope())
                {
                    weatherResponse.StatusCode.Should().Be(HttpStatusCode.NotFound);
                    weatherResponse.Forecasts.Should().BeNullOrEmpty();
                }
            });
        }
        public async void Can_get_qualified_bonuses()
        {
            var player = CreatePlayer();

            MakeDeposit(player.Id);
            CreateFirstDepositBonus(mode: IssuanceMode.ManualByCs);

            var request = new FilteredDataRequest
            {
                PageIndex  = 1,
                RowCount   = 20,
                SortSord   = "asc",
                SortColumn = "Name",
                TopRecords = 20,
                Filters    = new Filter[] {}
            };
            var result = await ApiProxy.GetFilteredIssueBonusesAsync(new PlayerFilteredDataRequest
            {
                DataRequest = request,
                PlayerId    = player.Id
            });

            result.Should().NotBeNull();
            result.Rows.Count.Should().BeGreaterOrEqualTo(1).And.BeLessOrEqualTo(20);
        }
        public void Cannot_get_template_edit_and_view_data_with_invalid_brand()
        {
            LogInApi(Guid.Empty);
            var template = CreateFirstDepositTemplate();

            AssertActionIsForbidden(() => ApiProxy.GetBonusTemplateRelatedDataAsync(template.Id));
        }
Example #5
0
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            var current = filterContext.RequestContext.HttpContext.Request.Cookies.Get("usertoken");

            if (current != null && !string.IsNullOrWhiteSpace(current.Value))
            {
                return;
            }
            else
            {
                var      guid     = Guid.NewGuid();
                ApiProxy p        = new ApiProxy();
                var      response = p.Post("api/account/settrackingtoken?Guid=" + guid.ToString());
                if (response.IsSuccessStatusCode)
                {
                    var cookie = new HttpCookie("usertoken")
                    {
                        Value = guid.ToString()
                    };
                    filterContext.RequestContext.HttpContext.Response.Cookies.Add(cookie);
                }
                else
                {
                    var logger = new Logger();
                    logger.Error("Error While Saving New Anon User", null);
                }
            }
        }
Example #6
0
        public IHttpActionResult GetTaskReminders()
        {
            TaskCountModel result = new TaskCountModel();

            result.TaskCount     = TaskWork.GetUseableTaskWork().Count(c => c.ReceiverAccount == ClientCookie.UserCode && c.Status == TaskWorkStatus.UnFinish);
            result.ReminderCount = Remind.Count(c => c.ReceiverAccount == ClientCookie.UserCode &&
                                                !c.IsReaded);
            result.NoticeCount = Notification.Count(ClientCookie.UserCode);
            //获取PMT任务数量
            string encryptUserCode = Cryptography.Encrypt(ClientCookie.UserCode, DateTime.Now.ToString("yyyyMMdd"), "oms");
            string redirectUrl     = string.Format(Constants.AM_To_PMT_RedirectUrl, "&eid=" + encryptUserCode);
            string callPMTTaskUrl  = string.Format(Constants.Get_PMT_TaskUrl, encryptUserCode);

            if (Constants.GetPMTTask)
            {
                var pmtTaskResult = ApiProxy.Call <PMTTaskCountModel>(callPMTTaskUrl);
                if (pmtTaskResult != null)
                {
                    result.PMT_ApproveCount = pmtTaskResult.ApproveCount;
                    result.PMT_DealCount    = pmtTaskResult.DealCount;
                    result.PMT_NotifyCount  = pmtTaskResult.NotifyCount;
                    result.PMT_RemindCount  = pmtTaskResult.RemindCount;
                    result.PMT_Total        = pmtTaskResult.Total;
                }
            }
            result.PMT_URL = redirectUrl;
            return(Ok(result));
        }
Example #7
0
        public static UserInfo Authenticate(string userId)
        {
            UserInfo userInfo = null;
            var      context  = HttpContext.Current;

            if (context.Session[SessionToken] != null)
            {
                userInfo = context.Session[SessionToken] as UserInfo;
            }
            else
            {
                string url = string.Format("{0}api/user/auth?userId={1}", ConfigurationManager.AppSettings["Fx.ServiceUri"], userId);
                userInfo = ApiProxy.Call <UserInfo>(url, "GET", null, null);
                context.Session[SessionToken] = userInfo;
                context.Session.Timeout       = 24 * 60;
            }

            HttpCookie cookieUser = new HttpCookie(CookieUserToken);

            cookieUser["Code"]      = userInfo.Code;
            cookieUser["NameZHCN"]  = HttpUtility.UrlEncode(userInfo.NameZHCN);
            cookieUser["NameENUS"]  = HttpUtility.UrlEncode(userInfo.NameENUS);
            cookieUser["TitleENUS"] = userInfo.TitleENUS;
            cookieUser.Expires      = DateTime.Now.AddMinutes(24 * 60);

            context.Response.Cookies.Add(cookieUser);
            return(userInfo);
        }
Example #8
0
        static void Main(string[] args)
        {
            try
            {
                // todo: move to config - might be stored in different places depending on the type of shell/UI
                string clientId     = "wBQyBvGi1nFj8b6KjN6mkXR0UDpGGprqv3rudsPVkBDqjh45EU";
                string clientSecret = "E57QB3uj2WcxAp9A1HSf9yTnH33PIhw6loh0GtpK";

                // Load the search parameters from an external JSON file.
                string jsonSearchParameters = File.ReadAllText("../../SearchFilters.json");
                var    searchParameters     = JsonConvert.DeserializeObject <AnimalSearchParameters>(jsonSearchParameters);

                ApiProxy proxy           = new ApiProxy(clientId, clientSecret);
                var      matchingAnimals = proxy.GetMatchingAnimals(searchParameters);

                foreach (var animal in matchingAnimals)
                {
                    Console.WriteLine($"{animal.name}:\t{animal.url}");
                    Console.WriteLine();
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }

            Console.ReadLine();
        }
Example #9
0
 public StationAgentUpdater(ApiSettings apiSettings, BaseRepositoryConfig repositoryConfig, OutsideWorldInteractionWorkerConfig outsideWorldConfig, ILogger logger)
 {
     _logger             = logger;
     _repositoryConfig   = repositoryConfig;
     _outsideWorldConfig = outsideWorldConfig;
     _apiProxy           = new ApiProxy(apiSettings, logger);
 }
Example #10
0
        private Tuple <int, string, string> Send(string url, HttpMethod httpMethod, Content content = null, bool isUseApiAddress = false)
        {
            var authenticationSite = new AuthenticationSite()
            {
                AuthenticationType = "Auth", Uuid = Guid.NewGuid().ToString()
            };

            _iAuthenticationServices.Add(authenticationSite);

            var client = new System.Net.Http.HttpClient();

            client.DefaultRequestHeaders.Add("Authorization", authenticationSite.Uuid);

            var apiException = new ApiException();

            var result = ApiProxy.Send(httpMethod, url, content, client, apiException, isUseApiAddress);

            var error = string.Empty;

            if (apiException.Code != 200)
            {
                if (apiException.Code == 404)
                {
                    error = $"参数保存失败,{url}地址不存在,请检查输入的域名地址{apiException.Code}";
                }
                else
                {
                    error = $"参数保存失败,{url}服务器错误 Code={apiException.Code}";
                }
            }
            return(new Tuple <int, string, string>(apiException.Code, error, result));
        }
Example #11
0
        public void Api_Submit_InvalidLocationRequest_ReturnsNotFound(string cityName,
                                                                      ApiProxy apiProxy,
                                                                      ILocationRequest locationRequest,
                                                                      ILocationResponse locationResponse)
        {
            $"Given a cityName value of {cityName}"
            .x(() => locationRequest = new LocationRequest {
                CityName = cityName
            });

            "And an ApiProxy".x(() => apiProxy = new ApiProxy(_metaWeatherService));

            "When the location request is submitted"
            .x(async() => locationResponse =
                   await apiProxy.SubmitLocationRequest(locationRequest).ConfigureAwait(false));

            "Then the location response should return HttpStatusCode.NotFound, and Locations should be empty"
            .x(() =>
            {
                using (new AssertionScope())
                {
                    locationResponse.StatusCode.Should().Be(HttpStatusCode.NotFound);
                    locationResponse.Locations.Should().BeNullOrEmpty();
                }
            });
        }
Example #12
0
        public void Api_Submit_ValidLocationRequest_ReturnsCorrectWoeid(string cityName,
                                                                        int expectedCount,
                                                                        int expectedWoeid,
                                                                        ApiProxy apiProxy,
                                                                        ILocationRequest locationRequest,
                                                                        ILocationResponse locationResponse)
        {
            $"Given a cityName value of {cityName}"
            .x(() => locationRequest = new LocationRequest {
                CityName = cityName
            });

            "And an ApiProxy"
            .x(() => apiProxy = new ApiProxy(_metaWeatherService));

            "When the location request is submitted"
            .x(async() => locationResponse =
                   await apiProxy.SubmitLocationRequest(locationRequest).ConfigureAwait(false));

            $"Then the location response should return HttpStatusCode.OK), CityName {cityName} and WoeId {expectedWoeid}"
            .x(() =>
            {
                using (new AssertionScope())
                {
                    locationResponse.StatusCode.Should().Be(HttpStatusCode.OK);
                    locationResponse.Locations.Should().HaveCount(expectedCount);
                    locationResponse.Locations[0].WoeId.Should().Be(expectedWoeid);
                }
            });
        }
        public async void Can_get_filtered_templates()
        {
            var template = CreateFirstDepositTemplate();

            var request = new FilteredDataRequest
            {
                PageIndex  = 1,
                RowCount   = 20,
                SortSord   = "asc",
                SortColumn = "Info.Name",
                TopRecords = 20,
                Filters    = new[]
                {
                    new Filter
                    {
                        Field      = "Info.Name",
                        Comparison = ComparisonOperator.Eq,
                        Data       = template.Info.Name
                    }
                }
            };
            var result = await ApiProxy.GetFilteredBonusTemplatesAsync(request);

            result.Should().NotBeNull();
            result.Rows.Count.Should().Be(1);
        }
        public async void Can_get_filtered_bonus_redemptions()
        {
            var player = CreatePlayer();
            var bonus  = CreateFirstDepositBonus(mode: IssuanceMode.AutomaticWithCode);

            MakeDeposit(player.Id, bonusCode: bonus.Code);

            var request = new FilteredDataRequest
            {
                PageIndex  = 1,
                RowCount   = 20,
                SortSord   = "asc",
                SortColumn = "Bonus.Name",
                TopRecords = 20,
                Filters    = null
            };
            var result = await ApiProxy.GetFilteredBonusRedemptionAsync(new PlayerFilteredDataRequest
            {
                PlayerId    = player.Id,
                DataRequest = request
            });

            result.Should().NotBeNull();
            result.Rows.Count.Should().BeGreaterOrEqualTo(1).And.BeLessOrEqualTo(20);
        }
Example #15
0
        protected override async void OnAppearing()
        {
            base.OnAppearing();

            await splashImage.ScaleTo(1, 2000);

            await splashImage.ScaleTo(0.9, 1500, Easing.Linear);

            await splashImage.ScaleTo(150, 1200, Easing.Linear);

            if (await LocalStorage.ReadTextFileAsync("Remember.txt") == "true")
            {
                isRemember = true;
            }
            else
            {
                isRemember = false;
            }

            if (isRemember)
            {
                var userName = await LocalStorage.ReadTextFileAsync("Username.txt");

                var pwrd = await LocalStorage.ReadTextFileAsync("Pwrd.txt");

                ApiProxy apiProxy = new ApiProxy();
                LoginPage.userInfo = await apiProxy.GetUser(userName, pwrd);

                Application.Current.MainPage = new NavigationPage(new MainPage());
            }
            else
            {
                Application.Current.MainPage = new NavigationPage(new LoginPage());
            }
        }
Example #16
0
        public void Api_Submit_ValidWeatherRequest_ReturnsForecasts(
            int woeId,
            int expectedCount,
            ApiProxy apiProxy,
            IWeatherRequest weatherRequest,
            IWeatherResponse weatherResponse)
        {
            $"Given a woeId value of {woeId}"
            .x(() => weatherRequest = new WeatherRequest {
                WoeId = woeId
            });

            "And an ApiProxy"
            .x(() => apiProxy = new ApiProxy(_metaWeatherService));

            "When the weather request is submitted"
            .x(
                async() => weatherResponse =
                    await apiProxy.SubmitWeatherRequest(weatherRequest).ConfigureAwait(false));

            $"Then the weather response should return StatusCode HttpStatusCode.OK), and contain {expectedCount} Forecasts"
            .x(
                () =>
            {
                using (new AssertionScope())
                {
                    weatherResponse.StatusCode.Should().Be(HttpStatusCode.OK);
                    weatherResponse.Forecasts.Should().HaveCount(expectedCount);
                }
            });
        }
        public async void Can_get_filtered_bonuses()
        {
            var bonus = CreateFirstDepositBonus(isActive: false);

            var request = new FilteredDataRequest
            {
                PageIndex  = 1,
                RowCount   = 20,
                SortSord   = "asc",
                SortColumn = "Name",
                TopRecords = 20,
                Filters    = new[]
                {
                    new Filter
                    {
                        Field      = "Name",
                        Comparison = ComparisonOperator.Eq,
                        Data       = bonus.Name
                    }
                }
            };
            var result = await ApiProxy.GetFilteredBonusesAsync(new BrandFilteredDataRequest
            {
                DataRequest  = request,
                BrandFilters = new List <Guid> {
                    DefaultBrandId
                }
            });

            result.Should().NotBeNull();
            result.Rows.Count.Should().Be(1);
        }
Example #18
0
        private async void btnLogin_Clicked(object sender, EventArgs e) //When login clicked, check if fields are empty, if not ...
        {
            if (String.IsNullOrEmpty(txtUsername.Text) || String.IsNullOrEmpty(txtPassword.Text))
            {
                await DisplayAlert("Error", "All fields must be filled", "Try Again");
            }
            else
            {
                ApiProxy apiProxy = new ApiProxy();

                var user = await apiProxy.GetUser(txtUsername.Text, txtPassword.Text); //send the username and password to the private api to see if it matches

                if (user != null)                                                      //If it matches and the user exists, add all of the users data into the model class of UserInfo to be used throughout the app, sending the user to home page
                {
                    userInfo = user;
                    if (chkRememberMe.IsChecked)
                    {
                        await LocalStorage.WriteTextFileAsync("Remember.txt", "true");

                        await LocalStorage.WriteTextFileAsync("Username.txt", user.Username);

                        await LocalStorage.WriteTextFileAsync("Pwrd.txt", user.Pword);
                    }
                    //await Navigation.PopModalAsync();
                    var page = Navigation.NavigationStack.LastOrDefault();
                    await Navigation.PushAsync(new MainPage());

                    Navigation.RemovePage(page);
                }
                else
                {
                    await DisplayAlert("Error", "Account not found", "Try Again"); //Otherwise account not found
                }
            }
        }
        /// <summary>
        /// Initializes a new instance of <see cref="RespContentApiClientBehavior"/>
        /// </summary>
        public RespContentApiClientBehavior(WebApplicationFactory <Startup> webApplicationFactory, ITestOutputHelper output)
        {
            _output = output;
            var clientProvider = new DelegateHttpClientProvider(webApplicationFactory.CreateClient);

            _client = new ApiClient <ITestServer>(clientProvider);
            _proxy  = ApiProxy <ITestServer> .Create(clientProvider);
        }
        public async void Can_delete_template()
        {
            var template = CreateFirstDepositTemplate();

            var result = await ApiProxy.DeleteBonusTemplateAsync(new DeleteTemplate { TemplateId = template.Id });

            result.Success.Should().BeTrue();
        }
        public void T_ClientProxyByGW(string apiUrl)
        {
            IApiProxy <IHelloWorldService> proxy = new ApiProxy <IHelloWorldService>(new Uri(apiUrl));

            proxy.ApiVersion = "1";
            proxy.RegisterChtSwaggerDoc(useApiGateway: true);
            CallApi(proxy);
        }
        public async void Can_get_template_add_data()
        {
            var result = await ApiProxy.GetBonusTemplateRelatedDataAsync();

            result.Should().NotBeNull();
            result.Template.Should().BeNull();
            result.Bonuses.Should().NotBeNull("Can not check for empty because it can be actually empty.");
        }
Example #23
0
        public async void Can_get_deposit_qualified_bonus_by_code()
        {
            var bonus = CreateFirstDepositBonus(mode: IssuanceMode.AutomaticWithCode);

            var result = await ApiProxy.GetDepositQualifiedBonusByCodeAsync(_player.Id, bonus.Code, 0);

            result.Name.Should().Be(bonus.Name);
        }
        public async Task ShouldPassWhenExpectedStatusCodeWithProxy()
        {
            //Arrange
            var client = ApiProxy <ITestServer> .Create(_clientProvider);

            //Act & Assert
            await client.GetExpected404();
        }
        public async Task <decimal> MinimumExchangeRateDuringPeriod(RequestModel requestModel)
        {
            string url    = $"https://api.exchangeratesapi.io/history?base={ requestModel.CurrencyPair.BaseCurrency }&start_at={ requestModel.DateRange.StartDate }&end_at={ requestModel.DateRange.EndDate }&symbols={ requestModel.CurrencyPair.TargetCurrency }";
            var    result = await ApiProxy.GetAsync(url);

            var ratesList = ResultToList(result);

            return(ratesList.Min());
        }
Example #26
0
        public Mostrar()
        {
            InitializeComponent();
            tokenContainer = new TokenContainer();
            var apiClient = new ApiProxy(HttpClientInstance.InstanceCommon, tokenContainer);

            usuarioProxy = new UsuarioProxy(apiClient);
            ObtenerUsuario();
        }
        public void Cannot_delete_template_with_invalid_brand()
        {
            LogInApi(Guid.Empty);
            var template = CreateFirstDepositTemplate();

            AssertActionIsForbidden(() => ApiProxy.DeleteBonusTemplateAsync(new DeleteTemplate {
                TemplateId = template.Id
            }));
        }
Example #28
0
        async public Task <string> Hello()
        {
            var proxy = new ApiProxy <IHelloWorldService>(_src, _loggerFactory);

            proxy.ApiVersion = "1";//
            //proxy.RegisterSwaggerDoc(new Uri(swaggerDocUrl));
            proxy.RegisterChtSwaggerDoc(useApiGateway: true);
            return(await Task.Run <string>(() => proxy.Svc.HelloGet("EEE", "FFF")));
        }
        public async void Can_get_bonuses()
        {
            var bonus = CreateFirstDepositBonus(mode: IssuanceMode.AutomaticWithCode);

            var result = await ApiProxy.GetBonusesAsync();

            result.Should().NotBeEmpty();
            result.Any(t => t.Id == bonus.Id).Should().BeTrue();
        }
        public void T_ClientProxy(string apiUrl, string swaggerDocUrl)
        {
            //var p=serviceProvider.GetRequiredService <IApiProxy<IHelloWorldService>>();
            var proxy = new ApiProxy <IHelloWorldService>(new Uri(apiUrl));

            proxy.ApiVersion = "1";
            proxy.RegisterSwaggerDoc(new Uri(swaggerDocUrl));
            CallApi(proxy);
        }
		public API_StackOverflow()
		{
			SOProxy = new ApiProxy();
		}