public void DelegatingHandlersAreCloned()
        {
            string userAccount = "*****@*****.**";
            Guid subscriptionId = Guid.NewGuid();
             AzureContext context = new AzureContext
            (
                new AzureSubscription()
                {
                    Account = userAccount,
                    Environment = "AzureCloud",
                    Id = subscriptionId,
                    Properties = new Dictionary<AzureSubscription.Property, string>() { { AzureSubscription.Property.Tenants, "common" } }
                }, 
                new AzureAccount()
                {
                    Id = userAccount,
                    Type = AzureAccount.AccountType.User,
                    Properties = new Dictionary<AzureAccount.Property, string>() { { AzureAccount.Property.Tenants, "common" } }
                },
                AzureEnvironment.PublicEnvironments["AzureCloud"]
            );

            AzureSession.AuthenticationFactory = new MockTokenAuthenticationFactory(userAccount, Guid.NewGuid().ToString());
            var mockHandler = new MockDelegatingHandler();
            var factory = new ClientFactory();
            factory.AddHandler(mockHandler);
            var client = factory.CreateClient<StorageManagementClient>(context, AzureEnvironment.Endpoint.ServiceManagement);
            client = factory.CreateClient<StorageManagementClient>(context, AzureEnvironment.Endpoint.ServiceManagement);
            client = factory.CreateClient<StorageManagementClient>(context, AzureEnvironment.Endpoint.ServiceManagement);
            client = factory.CreateClient<StorageManagementClient>(context, AzureEnvironment.Endpoint.ServiceManagement);
            client = factory.CreateClient<StorageManagementClient>(context, AzureEnvironment.Endpoint.ServiceManagement);
            Assert.Equal(5, MockDelegatingHandler.cloneCount); 
        }
Ejemplo n.º 2
0
        private async Task <List <Product> > DoSomething(ITracer tracer)
        {
            var client    = ClientFactory.CreateClient();
            var clientUrl = "http://localhost:5001/products";

            var outgoingRequest = new HttpRequestMessage(HttpMethod.Get, clientUrl);

            var outgoingSpan = tracer.StartSpan($"HTTP GET Start to call {clientUrl} to get products", SpanKind.Client);

            if (outgoingSpan.Context.IsValid)
            {
                tracer.TextFormat.Inject(
                    outgoingSpan.Context,
                    outgoingRequest.Headers,
                    (headers, name, value) => headers.Add(name, value));
            }

            var jsonData = await client.SendAsync(outgoingRequest);

            outgoingSpan.End();

            var products = JsonConvert.DeserializeObject <List <Product> >(await jsonData.Content.ReadAsStringAsync());

            return(products);
        }
Ejemplo n.º 3
0
        public void MockPushMethod()
        {
            var args       = Utils.GetTestArgs();
            var connection = new MockConnection();

            args.Connection = connection;
            var client = ClientFactory.CreateClient(args);

            client.BudgetVersion = new BudgetVersion();
            client.BudgetClient.ResetChanged();
            var addedTransaction = new Transaction
            {
                Amount = 12,
                Date   = DateTime.Now
            };

            client.Budget.Transactions.Add(addedTransaction);
            client.Push(1);

            Assert.Equal(2, connection.Requests.Count);
            Assert.Equal("syncCatalogData", connection.Requests[0].Opname);
            Assert.Equal("syncBudgetData", connection.Requests[1].Opname);


            var cchangedEntities = connection.Requests[0].Dict["changed_entities"] as Catalog;

            Assert.NotNull(cchangedEntities);
            Assert.Equal(0, cchangedEntities.Size);
            var bchangedEntities = connection.Requests[1].Dict["changed_entities"] as Budget;

            Assert.NotNull(bchangedEntities);
            Assert.Equal(1, bchangedEntities.Size);
            Assert.Equal(1, bchangedEntities.Transactions.Count);
            Assert.Equal(addedTransaction, bchangedEntities.Transactions[0]);
        }
Ejemplo n.º 4
0
        public static void Main(string[] args)
        {
            Console.Title = string.Format("Tcp-client test");

            var client = ClientFactory.CreateClient("127.0.0.1:1337");

            client.Connected       += ClientOnConnected;
            client.Disconnected    += ClientOnDisconnected;
            client.MessageReceived += ClientOnMessageReceived;
            client.MessageSent     += ClientOnMessageSent;
            client.Connect();

            do
            {
                var cmd = Console.ReadLine();
                if (cmd == "exit")
                {
                    client.Disconnect();
                }
                if (cmd == "testmsg")
                {
                    var msg = new TextMessage("Hello from client! äöüß");
                    client.SendMessage(msg);
                }
            } while (client.CommunicationState == CommunicationStates.Connected);


            Console.WriteLine("Press any key to exit.");
            Console.Read();
        }
Ejemplo n.º 5
0
        public async Task <T> ExecuteAsync <T>(IWeChatPayRequest <T> request) where T : WeChatPayResponse
        {
            // 字典排序
            var sortedTxtParams = new WeChatPayDictionary(request.GetParameters())
            {
                { mch_id, Options.MchId },
                { nonce_str, Guid.NewGuid().ToString("N") }
            };

            if (string.IsNullOrEmpty(sortedTxtParams.GetValue(appid)))
            {
                sortedTxtParams.Add(appid, Options.AppId);
            }

            sortedTxtParams.Add(sign, WeChatPaySignature.SignWithKey(sortedTxtParams, Options.Key));
            var content = WeChatPayUtility.BuildContent(sortedTxtParams);

            Logger?.LogTrace(0, "Request:{content}", content);

            using (var client = ClientFactory.CreateClient())
            {
                var body = await HttpClientUtility.DoPostAsync(client, request.GetRequestUrl(), content);

                Logger?.LogTrace(1, "Response:{body}", body);

                var parser = new WeChatPayXmlParser <T>();
                var rsp    = parser.Parse(body);
                CheckResponseSign(rsp);
                return(rsp);
            }
        }
Ejemplo n.º 6
0
        public TokenBasedClientTests()
        {
            var testConfig    = new TestConfiguration();
            var clientFactory = new ClientFactory(testConfig.ApplicationId);

            _client = clientFactory.CreateClient(testConfig.TokenPassportProvider);
        }
        private JToken LoadDiscoveryFile(string uri, DocumentSourceType type)
        {
            return(JToken.Parse(GetContent(type)));

            string GetContent(DocumentSourceType source)
            {
                switch (source)
                {
                case DocumentSourceType.File:
                    return(File.ReadAllText(uri));

                case DocumentSourceType.Directory:
                    throw new NotSupportedException(
                              $"Discovery may only be used with files and web-resources. '{uri}' is a directory.");

                case DocumentSourceType.Web:
                    var client = ClientFactory.CreateClient();
                    return(client.GetStringAsync(uri).Result);

                case DocumentSourceType.Unknown:
                    throw new Exception("Unable to determine type of URI for discovery file.");

                default:
                    throw new ArgumentOutOfRangeException();
                }
            }
        }
        private Task <string> LoadSpecsAsync(string specUrl)
        {
            var client         = ClientFactory.CreateClient();
            var hasAbsoluteUri = TryGetAbsoluteSpecUri(specUrl, out var uri);

            if (!hasAbsoluteUri)
            {
                return(Task.FromResult((string)null));
            }

            var response = client.GetAsync(uri);

            return(response.ContinueWith(GetResponseContent).Unwrap());

            Task <string> GetResponseContent(Task <HttpResponseMessage> x)
            {
                if (x.Result.IsSuccessStatusCode)
                {
                    return(x.Result.Content.ReadAsStringAsync());
                }
                else
                {
                    LogSpecLoadingError(uri.ToString(), x.Result.StatusCode);
                    return(Task.FromResult((string)null));
                }
            }
        }
Ejemplo n.º 9
0
        //Get LeagueTeams, TeamUsers, and LeagueActivity into a list and returns to the page
        public async Task <IActionResult> OnGetAsync(int leagueId)
        {
            GetLeague = await Context.GetLeaguesAsync(leagueId);

            GetTeam = await Context.GetTeamsAsync(leagueId, UserManager.GetUserId(User));

            if (GetLeague == null)
            {
                ViewData["ErrorMessage"] = $"League not found";
            }

            if (GetLeague == null)
            {
                ViewData["ErrorMessage"] = $"Team not found";
            }



            string baseURL   = HTTPURI + "2019/segments/0/leagues/584314?forTeamId=2&scoringPeriodId=13&view=mRoster";
            var    request   = new HttpRequestMessage(HttpMethod.Get, baseURL);
            var    webClient = ClientFactory.CreateClient("ESPN");
            var    response  = await webClient.SendAsync(request);

            if (response.IsSuccessStatusCode)
            {
                var JsonString = await response.Content.ReadAsStringAsync();

                GetESPNRoster = JsonConvert.DeserializeObject <ESPNRoster>(JsonString);
            }



            return(Page());
        }
Ejemplo n.º 10
0
        public async Task WhenCreatingPredecessorCircle_RespondsWithCreate()
        {
            var client             = ClientFactory.CreateClient();
            var predecessorRequest = CreateValidRequest();

            // Arrange: Create entry with follow-up
            var predecessor = await CreateValidEntry(client, predecessorRequest).ConfigureAwait(true);

            predecessor.Should().NotBeNull();
            predecessor !.Id.Should().BeGreaterThan(0);
            var followUp = CreateValidRequest();

            followUp.PredecessorLaboratoryNumber = predecessor !.LaboratoryNumber;
            var followUpEntry = await CreateValidEntry(client, followUp).ConfigureAwait(true);

            followUpEntry.Should().NotBeNull();

            // Arrange: Make original entry reference follow-up, thus creating a circle
            predecessorRequest.Id = predecessor !.Id;
            predecessorRequest.PredecessorLaboratoryNumber = followUpEntry !.LaboratoryNumber;

            var circleResponse = await client.PutAsJsonAsync("api/sentinel-entries", predecessorRequest).ConfigureAwait(true);

            circleResponse.StatusCode.Should().Be(HttpStatusCode.OK);
            predecessor = await client.GetFromJsonAsync <SentinelEntryResponse>($"api/sentinel-entries/{predecessor.Id}").ConfigureAwait(true);

            predecessor.PredecessorLaboratoryNumber.Should().Be(followUpEntry !.LaboratoryNumber);
        }
        /// <summary>
        /// WEATHER INFORMATION FROM OPENWEATHER REST API ENDPOINT!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
        /// </summary>
        public async Task <string> FetchWeatherApi(Park park)
        {
            string weatherKey = _configuration["OpenWeatherKey"];
            var    request    = new HttpRequestMessage(HttpMethod.Get,
                                                       $"https://api.openweathermap.org/data/2.5/weather?lat={park.ParkLatitude}&lon={park.ParkLongitude}&APPID={weatherKey}");

            var client = ClientFactory.CreateClient("weather");
            HttpResponseMessage response = await client.SendAsync(request);

            if (response.IsSuccessStatusCode)
            {
                RestParks = await response.Content.ReadFromJsonAsync <RestApiOpenWeather>();

                park.CurrentWeatherInfo.Temperature = GetCurrentTemperature(Convert.ToDouble(RestParks.Main.Temp));
                park.CurrentWeatherInfo.Condition   = RestParks.Weather[0].Main;
                park.CurrentWeatherInfo.Wind        = Math.Round(RestParks.Wind.Speed, 2);
                await _context.SaveChangesAsync();

                return(await response.Content.ReadAsStringAsync());
            }
            else
            {
                return($"Status Code: {response.StatusCode}");
            }
        }
        /// <summary>
        /// HIKING TRAIL INFORMATION FROM HIKING DATA PROJECT REST API ENDPOINT!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
        /// </summary>
        public async Task <string> FetchTrailsApi(int id)
        {
            Park park = await _context.Parks.FindAsync(id);

            var hikingTrailsKey = _configuration["HikingProjectKey"];
            var request         = new HttpRequestMessage(HttpMethod.Get,
                                                         $"https://www.hikingproject.com/data/get-trails?lat={park.ParkLatitude}&lon={park.ParkLongitude}&maxDistance=50&maxResults=60&key={hikingTrailsKey}");

            var client = ClientFactory.CreateClient("trails");
            HttpResponseMessage response = await client.SendAsync(request);

            if (response.IsSuccessStatusCode)
            {
                RestApiHikingProject RestTrails = await response.Content.ReadFromJsonAsync <RestApiHikingProject>();

                List <Trail> trailInfo = RestTrails.Trails.ToList();
                await ApplyHikingTrailValues(park, trailInfo);

                await _context.SaveChangesAsync();

                return(await response.Content.ReadAsStringAsync());
            }
            else
            {
                return($"Status Code: {response.StatusCode}");
            }
        }
        public async Task <PostalCodeDto> GetCityNameByPostalCodeAsync(string postalCode)
        {
            try
            {
                var request = new HttpRequestMessage(HttpMethod.Get, $"{Settings.Uri}/{postalCode}/json");

                var client = ClientFactory.CreateClient();

                var response = await client.SendAsync(request);

                if (!response.IsSuccessStatusCode)
                {
                    return new PostalCodeDto {
                               HasFailed = true
                    }
                }
                ;
                return(await response.Content.ReadAsAsync <PostalCodeDto>());
            }
            catch
            {
                return(new PostalCodeDto {
                    HasFailed = true
                });
            }
        }
        public IEnumerable <OpenApiDocument> GetDocuments()
        {
            var client = ClientFactory.CreateClient();
            var spec   = client.GetStringAsync(Uri).Result;

            yield return(OpenApiDocumentUtils.ReadSpec(spec));
        }
Ejemplo n.º 15
0
        public async Task <IEnumerable <GitCommitRef> > GetLastCommitsAsync(
            Guid serviceId,
            Guid repositoryId,
            string branch,
            int top = 10,
            CancellationToken cancellationToken = default)
        {
            AzureDevOpsConnectedService service = await ClientFactory.ConnectAsync(
                serviceId,
                cancellationToken);

            GitHttpClient client = ClientFactory.CreateClient <GitHttpClient>(serviceId);

            return(await client.GetCommitsAsync(
                       service.DefaultProject,
                       repositoryId,
                       new GitQueryCommitsCriteria()
            {
                ItemVersion = new GitVersionDescriptor()
                {
                    VersionType = GitVersionType.Branch,
                    VersionOptions = GitVersionOptions.None,
                    Version = branch
                },
                IncludeLinks = true
            },
                       top : top,
                       cancellationToken : cancellationToken)
                   .ConfigureAwait(false));
        }
        public NetSuiteClientTests()
        {
            var config  = new TestConfiguration();
            var factory = new ClientFactory(config.ApplicationId);

            client = factory.CreateClient(config.PassportProvider);
        }
Ejemplo n.º 17
0
        private async Task CallWebHook(ILambdaContext context, NotificationMessage message)
        {
            context.Logger.LogLine($"@@@ Calling Webhook {Subscription.WebHookUrl}");

            var request = new HttpRequestMessage(HttpMethod.Post, Subscription.WebHookUrl);

            var stringContent = new StringContent(JsonConvert.SerializeObject(message), Encoding.UTF8, "application/json");

            request.Content = stringContent;

            HttpClient clientRest = ClientFactory.CreateClient();

            clientRest.DefaultRequestHeaders
            .Accept
            .Add(new MediaTypeWithQualityHeaderValue("application/json"));            //ACCEPT header

            HttpResponseMessage response = await clientRest.SendAsync(request);

            context.Logger.LogLine($"@@@ Called Webhook {Subscription.WebHookUrl}");


            string execStatus = "Executed";

            if (!response.IsSuccessStatusCode)
            {
                context.Logger.LogLine($"#### Erro: calling Webhook {Subscription.WebHookUrl}");
                execStatus = "Error";
            }



            await NotificationFactory(context, message, execStatus);

            context.Logger.LogLine($"Begin CreateNotification: message.NotifyId {message.NotifyId}");
        }
Ejemplo n.º 18
0
        public JetBoxOptionsPage(Lifetime lifetime, IUIApplication environment, ClientFactory clientFactory, JetBoxSettingsStorage jetBoxSettings, JetPopupMenus jetPopupMenus, OpensUri opensUri)
            : base(lifetime, environment, PID)
        {
            mySettingsStore = jetBoxSettings.SettingsStore.BindToContextLive(lifetime, ContextRange.ApplicationWide);
            myOpensUri      = opensUri;

            myClient           = clientFactory.CreateClient();
            myClient.UserLogin = mySettingsStore.GetValue(JetBoxSettingsAccessor.Login);

            // init UI
            myLoggedPanel = new FlowLayoutPanel {
                Visible = false, AutoSize = true
            };
            myLoggedPanel.Controls.Add(myLoginLabel = new RichTextLabel(environment));
            myLoggedPanel.Controls.Add(new LinkLabel("Logout", Logout, jetPopupMenus));

            myNonLoggedPanel = new FlowLayoutPanel {
                Visible = false, AutoSize = true, FlowDirection = FlowDirection.TopDown
            };
            myNonLoggedPanel.Controls.Add(new LinkLabel("Login", Login, jetPopupMenus));
            myNonLoggedPanel.Controls.Add(new LinkLabel("Get access (click after approving access on the web)", GetInfo, jetPopupMenus));

            Controls.Add(myLoggedPanel);
            Controls.Add(myNonLoggedPanel);

            InitLoginState();
        }
Ejemplo n.º 19
0
        public async Task <T> ExecuteAsync <T>(IQPayCertificateRequest <T> request, string certificateName = "Default") where T : QPayResponse
        {
            // 字典排序
            var sortedTxtParams = new QPayDictionary(request.GetParameters())
            {
                { MCHID, Options.MchId },
                { NONCE_STR, Guid.NewGuid().ToString("N") }
            };

            if (string.IsNullOrEmpty(sortedTxtParams.GetValue(APPID)))
            {
                sortedTxtParams.Add(APPID, Options.AppId);
            }

            sortedTxtParams.Add(SIGN, QPaySignature.SignWithKey(sortedTxtParams, Options.Key));
            var content = QPayUtility.BuildContent(sortedTxtParams);

            Logger?.LogTrace(0, "Request:{content}", content);

            using (var client = ClientFactory.CreateClient(QPayOptions.CertificateClientName + "." + certificateName))
            {
                var body = await HttpClientUtility.DoPostAsync(client, request.GetRequestUrl(), content);

                Logger?.LogTrace(1, "Response:{body}", body);

                var parser = new QPayXmlParser <T>();
                var rsp    = parser.Parse(body);
                CheckResponseSign(rsp);
                return(rsp);
            }
        }
Ejemplo n.º 20
0
        /// <summary>
        /// 创建gRPC服务
        /// </summary>
        /// <typeparam name="T">服务类型</typeparam>
        /// <param name="channel">gRPC信道</param>
        /// <returns>gRPC服务实例</returns>
        public static T CreateGrpcService <T>(this ChannelBase channel) where T : class
        {
            IClientFactory clientFactory = new ClientFactory();
            T serviceInstance            = clientFactory.CreateClient <T>(channel);

            return(serviceInstance);
        }
        /// <summary>
        /// PARK INFORMATION FROM NPS REST API ENDPOINT!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
        /// </summary>
        public async Task <string> FetchParksApi()
        {
            var parksKey = _configuration["NpsKey"];
            var request  = new HttpRequestMessage(HttpMethod.Get,
                                                  $"https://developer.nps.gov/api/v1/parks?q=National%20Park&limit=91&api_key={parksKey}");

            var client = ClientFactory.CreateClient("parks");
            HttpResponseMessage response = await client.SendAsync(request);

            if (response.IsSuccessStatusCode)
            {
                RestApiNationalParks RestParks = await response.Content.ReadFromJsonAsync <RestApiNationalParks>();

                var parkInfo = RestParks.Data.Select(m => m).ToList();
                await ApplyParkValues(parkInfo);

                await _context.SaveChangesAsync();

                return(await response.Content.ReadAsStringAsync());
            }
            else
            {
                return($"Status Code: {response.StatusCode}");
            }
        }
Ejemplo n.º 22
0
    public Response DoSomething(string projectId)
    {
        string baseUrl = SomeOtherService.GetBaseUrlByProjectId(projectId);
        var    client  = _factory.CreateClient(baseUrl);

        return(client.GetQuestionsAsync(projectId));
    }
Ejemplo n.º 23
0
        public JetBoxOptionsPage(Lifetime lifetime, IUIApplication environment, ClientFactory clientFactory, JetBoxSettingsStorage jetBoxSettings, JetPopupMenus jetPopupMenus)
            : base(lifetime, environment, PID)
        {
            mySettingsStore = jetBoxSettings.SettingsStore.BindToContextLive(lifetime, ContextRange.ApplicationWide);
            myLifetimes     = new SequentialLifetimes(lifetime);

            myClient           = clientFactory.CreateClient();
            myClient.UserLogin = mySettingsStore.GetValue(JetBoxSettingsAccessor.Login);

            // init UI
            myLoggedPanel = new FlowLayoutPanel {
                Visible = false, AutoSize = true
            };
            myLoggedPanel.Controls.Add(myLoginLabel = new RichTextLabel(environment));
            myLoggedPanel.Controls.Add(new LinkLabel("Logout", Logout, jetPopupMenus));

            myNonLoggedPanel = new FlowLayoutPanel {
                Visible = false, AutoSize = true, FlowDirection = FlowDirection.TopDown
            };
            myNonLoggedPanel.Controls.Add(new LinkLabel("Login", Login, jetPopupMenus)
            {
                Image      = Environment.Theming.Icons[UnnamedThemedIcons.Dropbox.Id].CurrentGdipBitmapNotSure(),
                ImageAlign = ContentAlignment.MiddleLeft,
                Padding    = new Padding(20, 0, 0, 0)
            });

            Controls.Add(myLoggedPanel);
            Controls.Add(myNonLoggedPanel);

            InitLoginState();
        }
Ejemplo n.º 24
0
        public void TestMethod1()
        {
            var args   = Utils.GetTestArgs();
            var client = ClientFactory.CreateClient(args);

            client.Sync();
        }
Ejemplo n.º 25
0
        public async Task WhenAccessingIndex_ReturnsPage()
        {
            var client = ClientFactory.CreateClient();

            var response = await client.GetAsync("swagger/index.html").ConfigureAwait(true);

            response.StatusCode.Should().Be(HttpStatusCode.OK);
        }
Ejemplo n.º 26
0
        public void FailsToConvertInvalidGuidConfiguration()
        {
            IConfiguration configuration = GetConfiguration(new KeyValuePair <string, string>("guid", "no it its not"));

            var clientOptions = new TestClientOptions();

            Assert.Throws <FormatException>(() => ClientFactory.CreateClient(typeof(TestClient), typeof(TestClientOptions), clientOptions, configuration, null));
        }
Ejemplo n.º 27
0
        private async Task <ResponseContext> Proxy(RouteContext ctx, string host)
        {
            var client  = ClientFactory.CreateClient();
            var request = CreateRequest(ctx, host);

            var response = await client.SendAsync(request).ConfigureAwait(false);

            return(await CreateResponseAsync(response).ConfigureAwait(false));
        }
Ejemplo n.º 28
0
        public async Task <T> ExecuteAsync <T>(IJDPayRequest <T> request) where T : JDPayResponse
        {
            // 字典排序
            var sortedTxtParams = new JDPayDictionary(request.GetParameters());

            var content = BuildEncryptXml(request, sortedTxtParams);

            Logger?.LogTrace(0, "Request:{content}", content);

            using (var client = ClientFactory.CreateClient(JDPayOptions.DefaultClientName))
            {
                var body = await HttpClientUtility.DoPostAsync(client, request.GetRequestUrl(), content);

                Logger?.LogTrace(1, "Response:{content}", body);

                var parser = new JDPayXmlParser <T>();
                var rsp    = parser.Parse(JDPayUtility.FotmatXmlString(body));
                if (!string.IsNullOrEmpty(rsp.Encrypt))
                {
                    var encrypt          = rsp.Encrypt;
                    var base64EncryptStr = Encoding.UTF8.GetString(Convert.FromBase64String(encrypt));
                    var reqBody          = JDPaySecurity.DecryptECB(base64EncryptStr, Options.DesKeyBase64);
                    Logger?.LogTrace(2, "Encrypt Content:{body}", reqBody);

                    var reqBodyDoc = new XmlDocument()
                    {
                        XmlResolver = null
                    };
                    reqBodyDoc.LoadXml(reqBody);

                    var sign     = JDPayUtility.GetValue(reqBodyDoc, "sign");
                    var rootNode = reqBodyDoc.SelectSingleNode("jdpay");
                    var signNode = rootNode.SelectSingleNode("sign");
                    rootNode.RemoveChild(signNode);

                    var reqBodyStr = JDPayUtility.ConvertXmlToString(reqBodyDoc);
                    var xmlh       = rsp.Body.Substring(0, rsp.Body.IndexOf("<jdpay>"));
                    if (!string.IsNullOrEmpty(xmlh))
                    {
                        reqBodyStr = reqBodyStr.Replace("<?xml version=\"1.0\" encoding=\"UTF-8\"?>", xmlh);
                    }
                    var sha256SourceSignString = SHA256.Compute(reqBodyStr);
                    var decryptByte            = RSA_ECB_PKCS1Padding.Decrypt(Convert.FromBase64String(sign), Options.PublicKey);
                    var decryptStr             = JDPaySecurity.BytesToString(decryptByte);
                    if (sha256SourceSignString == decryptStr)
                    {
                        rsp         = parser.Parse(reqBody);
                        rsp.Encrypt = encrypt;
                    }
                    else
                    {
                        throw new Exception("sign check fail: check Sign and Data Fail!");
                    }
                }
                return(rsp);
            }
        }
Ejemplo n.º 29
0
        private async Task <ResultDto <PersonalProfileDto> > GetPersonalProfile(string profileCode)
        {
            var client = ClientFactory.CreateClient("BackendApi");

            return(await client.GetFromJsonAsync <ResultDto <PersonalProfileDto> >($"api/perfilpersonal/{profileCode}", new JsonSerializerOptions
            {
                PropertyNameCaseInsensitive = true
            }));
        }
Ejemplo n.º 30
0
 public async Task <IActionResult> Index(int instructorId)
 {
     using (var httpClient = ClientFactory.CreateClient("GeorestApi"))
     {
         var georestClient = new GeorestClient(httpClient.BaseAddress.ToString(), httpClient);
         ViewBag.InstructorResponses = await georestClient.GetAllInstructorResponsesAsync();
     }
     return(View());
 }
Ejemplo n.º 31
0
 public async Task <IActionResult> Index(int studentId)
 {
     using (var httpClient = ClientFactory.CreateClient("GeorestApi"))
     {
         var georestClient = new GeorestClient(httpClient.BaseAddress.ToString(), httpClient);
         ViewBag.StudentLabs = await georestClient.GetLabsForStudentAsync(studentId);
     }
     return(View());
 }
        public void VerifyUserAgentValuesAreTransmitted()
        {
            var storedClientFactory = AzureSession.ClientFactory;
            var storedAuthFactory = AzureSession.AuthenticationFactory;
            try
            {
                var authFactory = new AuthenticationFactory();
                authFactory.TokenProvider = new MockAccessTokenProvider(Guid.NewGuid().ToString(), "*****@*****.**");
                AzureSession.AuthenticationFactory = authFactory;
                var factory = new ClientFactory();
                AzureSession.ClientFactory = factory;
                factory.UserAgents.Clear();
                factory.AddUserAgent("agent1");
                factory.AddUserAgent("agent1", "1.0.0");
                factory.AddUserAgent("agent1", "1.0.0");
                factory.AddUserAgent("agent1", "1.9.8");
                factory.AddUserAgent("agent2");
                Assert.Equal(4, factory.UserAgents.Count);
                var client = factory.CreateClient<NullClient>(new AzureContext(
                    new AzureSubscription
                    {
                        Id = Guid.NewGuid(),
                        Properties = new Dictionary<AzureSubscription.Property, string>
                        {
                            {AzureSubscription.Property.Tenants, "123"}
                        }
                    },
                    new AzureAccount
                    {
                        Id = "*****@*****.**",
                        Type = AzureAccount.AccountType.User,
                        Properties = new Dictionary<AzureAccount.Property, string>
                        {
                            {AzureAccount.Property.Tenants, "123"}
                        }
                    },
                    AzureEnvironment.PublicEnvironments["AzureCloud"]

                    ), AzureEnvironment.Endpoint.ResourceManager);
                Assert.Equal(5, client.HttpClient.DefaultRequestHeaders.UserAgent.Count);
                Assert.True(client.HttpClient.DefaultRequestHeaders.UserAgent.Contains(new ProductInfoHeaderValue("agent1", "")));
                Assert.True(client.HttpClient.DefaultRequestHeaders.UserAgent.Contains(new ProductInfoHeaderValue("agent1", "1.0.0")));
                Assert.True(client.HttpClient.DefaultRequestHeaders.UserAgent.Contains(new ProductInfoHeaderValue("agent1", "1.9.8")));
                Assert.True(client.HttpClient.DefaultRequestHeaders.UserAgent.Contains(new ProductInfoHeaderValue("agent2", "")));
            }
            finally
            {
                AzureSession.ClientFactory = storedClientFactory;
                AzureSession.AuthenticationFactory = storedAuthFactory;
            }
        }