Example #1
0
 private void GetClientEndpoint()
 {
     var clientFactory = new ClientFactory();
     var clientConfig = new ClientConfiguration();
     clientConfig.MaxSessions = 10;
     client = clientFactory.MakeNew(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 3000), clientConfig);
 }
        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); 
        }
        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;
            }
        }
 static AzureSession()
 {
     ClientFactory = new ClientFactory();
     AuthenticationFactory = new AuthenticationFactory();
     CurrentContext = new AzureContext();
     CurrentContext.Environment = AzureEnvironment.PublicEnvironments[EnvironmentName.AzureCloud];
     AzureSession.OldProfileFile = "WindowsAzureProfile.xml";
     AzureSession.OldProfileFileBackup = "WindowsAzureProfile.xml.bak";
     AzureSession.ProfileDirectory = Path.Combine(
         Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
         Resources.AzureDirectoryName); ;
     AzureSession.ProfileFile = "AzureProfile.json";
     AzureSession.TokenCacheFile = "TokenCache.dat";
 }
 static AzureSession()
 {
     ClientFactory = new ClientFactory();
     AuthenticationFactory = new AuthenticationFactory();
     DataStore = new MemoryDataStore();
     TokenCache = new TokenCache();
     OldProfileFile = "WindowsAzureProfile.xml";
     OldProfileFileBackup = "WindowsAzureProfile.xml.bak";
     ProfileDirectory = Path.Combine(
         Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
         Resources.AzureDirectoryName); ;
     ProfileFile = "AzureProfile.json";
     TokenCacheFile = "TokenCache.dat";
 }
        public static IMetaService CreateMeta(string ip, int port)
        {
            try
            {
                var channel = new ClientFactory<IMetaService>().CreateConnection(String.Format("{0}:{1}", ip, port), "MPExtended/MetaService");
                if (!channel.TestConnection())
                    return null;

                return channel;
            }
            catch (Exception)
            {
                return null;
            }
        }
Example #7
0
        static void Main(string[] args)
        {
            var r = new ServiceFactory(ServicesConfiguration.LoadFromJson("services.config.json"));
            var host1 = r.CreateHost<ServiceA>();
            host1.Open();

            var host2 = r.CreateHost<ServiceB>();
            host2.Open();

            var cli1 = new ClientFactory(ClientsConfiguration.LoadFromJson("clients.config.json")).CreateClient<IServiceA>();
            Console.WriteLine(cli1.Operation1());

            Console.WriteLine("Services are created and listening. Press ENTER to terminate...");
            Console.ReadLine();
            host1.Close();
            host2.Close();
        }
Example #8
0
 public void CreateCollectionTest()
 {
     var builder = new ClientFactory();
      var result1 = new ClientSettings(ClientType.Legacy)
                {
                   LegacyClientSubType = LegacyClientSubType.Path,
                   Name = "Client 1",
                   Path = @"\\test\path1\"
                };
      var result2 = new ClientSettings(ClientType.Legacy)
                {
                   LegacyClientSubType = LegacyClientSubType.Http,
                   Name = "Client 2",
                   Path = @"\\test\path2\"
                };
      var result3 = new ClientSettings(ClientType.Legacy)
                {
                   LegacyClientSubType = LegacyClientSubType.Ftp
                };
      var instances = builder.CreateCollection(new[] { result1, result2, result3 });
      Assert.AreEqual(2, instances.Count());
 }
Example #9
0
 public void CreateCollectionTest()
 {
    var legacyClientFactory = MockRepository.GenerateStub<ILegacyClientFactory>();
    legacyClientFactory.Stub(x => x.Create()).Return(new LegacyClient());
    var builder = new ClientFactory { LegacyClientFactory = legacyClientFactory };
    var result1 = new ClientSettings(ClientType.Legacy)
                  {
                     LegacyClientSubType = LegacyClientSubType.Path,
                     Name = "Client 1",
                     Path = @"\\test\path1\"
                  };
    var result2 = new ClientSettings(ClientType.Legacy)
                  {
                     LegacyClientSubType = LegacyClientSubType.Http,
                     Name = "Client 2",
                     Path = @"\\test\path2\"
                  };
    var result3 = new ClientSettings(ClientType.Legacy)
                  {
                     LegacyClientSubType = LegacyClientSubType.Ftp
                  };
    var instances = builder.CreateCollection(new[] { result1, result2, result3 });
    Assert.AreEqual(2, instances.Count());
 }
Example #10
0
 public HttpClient CreateHttpClient(string endpoint, ICredentials credentials)
 {
     return(CreateHttpClient(endpoint, ClientFactory.CreateHttpClientHandler(endpoint, credentials)));
 }
Example #11
0
        protected override async Task OnInitializedAsync()
        {
            var client = ClientFactory.CreateClient("ServerAPI");

            LikeResult = await client.GetFromJsonAsync <LikingDto>($"/api/liking/{Id}");
        }
Example #12
0
 internal static List <ChannelEndpointElement> GetClientConfigurationNames <T>()
 {
     return(ClientFactory.GetClientConfigurationNames <T>(_configDictionary));
 }
Example #13
0
 public void CreateArgumentNullTest()
 {
     var builder = new ClientFactory();
      builder.Create(null);
 }
        public async void ShouldReturnAJObjectRepresentingTheTransactionStack()
        {
            var result = await ExecuteAsync(ClientFactory.GetClient());

            Assert.NotNull(result);
        }
Example #15
0
 public void Create_LegacyClientFactoryNull_Test()
 {
    var builder = new ClientFactory();
    var settings = new ClientSettings(ClientType.Legacy)
    {
       Name = "LegacyClient",
       Path = @"\\test\path\"
    };
    var instance = builder.Create(settings);
    Assert.IsNull(instance);
 }
Example #16
0
 public void CreatePathEmptyTest()
 {
     var builder = new ClientFactory();
      builder.Create(new ClientSettings(ClientType.Legacy)
                 {
                    Name = "Client 1"
                 });
 }
        public async void ShouldReturnAJObject()
        {
            var result = await ExecuteAsync(ClientFactory.GetClient());

            Assert.NotNull(result);
        }
        public static HttpClient GetHttplClient(string str)
        {
            HttpClient client = ClientFactory.GetHttplClient(str);

            return(client);
        }
Example #19
0
 public CarPaymentsController()
 {
     _clientFactory = new ClientFactory();
 }
Example #20
0
 public void OneTimeSetup()
 {
     FleetManagerClient = ClientFactory.CreateTcpFleetManagerClient(new EndpointSettings(IPAddress.Loopback));
 }
Example #21
0
        public async void ShouldDecodeTheBlockRplAsJObject()
        {
            var result = await ExecuteAsync(ClientFactory.GetClient());

            Assert.NotNull(result);
        }
Example #22
0
 public PerformanceChild(Logger logger, int id)
 {
     client  = ClientFactory.Create(logger);
     this.id = id;
     Tag     = "client" + id;
 }
Example #23
0
        public async Task<IActionResult> Post(OrderCreationInputModel2 model)
        {
            var userId = long.Parse(User.Claims.First(x => x.Type == "sub").Value);
            var client = ClientFactory.CreateClient();
            var transactionId = Generator.Generate();
            var productId = long.Parse(model.ProductId);

            var jsonSerializerOptions = new JsonSerializerOptions
            {
                PropertyNamingPolicy = JsonNamingPolicy.CamelCase
            };

            var productInfoResp = await client.GetAsync($"{Configuration["Product"]}/products/{productId}");
            var productInfoContent = await productInfoResp.Content.ReadAsStringAsync();
            if (!productInfoResp.IsSuccessStatusCode)
            {
                Logger.LogError("获取产品信息失败, {message}", productInfoContent);
                return StatusCode(500, new ApiErrorResult<ApiError>(new ApiError("ServerError", "获取产品信息失败")));
            }

            var productInfo = JsonSerializer.Deserialize<ApiResult<ProductViewModel>>(productInfoContent, jsonSerializerOptions).Value;

            // 仅适用于演示
            var saleTask = client.PostAsync($"{Configuration["Product"]}/transactions",
                new StringContent(JsonSerializer.Serialize(new ProductReserveInputModel
                {
                    UserId = userId,
                    TransactionId = transactionId,
                    ProductId = productId,
                    Qty = 1
                }), Encoding.UTF8, "application/json"));

            var orderTask = client.PostAsync($"{Configuration["Order"]}/transactions",
                new StringContent(JsonSerializer.Serialize(new OrderCreationInputModel
                {
                    UserId = userId,
                    TransactionId = transactionId,
                    Items = new List<OrderItemCreationInputModel>
                    {
                        new OrderItemCreationInputModel
                        {
                            ProductId = productId,
                            Qty = 1,
                            Price = productInfo.Price,
                            Image = productInfo.Image,
                            Name = productInfo.Name
                        }
                    }
                }), Encoding.UTF8, "application/json"));

            var billTask = client.PostAsync($"{Configuration["Payment"]}/transactions",
                new StringContent(JsonSerializer.Serialize(new BillCreationInputModel
                {
                    UserId = userId,
                    TransactionId = transactionId,
                    Amount = -productInfo.Price
                }), Encoding.UTF8, "application/json"));

            Task.WaitAll(saleTask, orderTask, billTask);

            var saleResult = await saleTask.Result.Content.ReadAsStringAsync();
            var orderResult = await orderTask.Result.Content.ReadAsStringAsync();
            var billResult = await billTask.Result.Content.ReadAsStringAsync();

            Logger.LogInformation("产品系统返回结果: {code} {json}", saleTask.Result.StatusCode, saleResult);
            Logger.LogInformation("订单系统返回结果: {code} {json}", orderTask.Result.StatusCode, orderResult);
            Logger.LogInformation("账单系统返回结果: {code} {json}", billTask.Result.StatusCode, billResult);

            if (!saleTask.Result.IsSuccessStatusCode)
            {
                var apiResult = JsonSerializer.Deserialize<ApiErrorResult<ApiError>>(saleResult, jsonSerializerOptions);
                if (apiResult.Error.Code.Equals("OutOfStock", StringComparison.OrdinalIgnoreCase))
                {
                    return BadRequest(apiResult); // 等待系统自动撤销账单
                }

                throw new NotImplementedException();
            }

            if (!billTask.Result.IsSuccessStatusCode)
            {
                var apiResult = JsonSerializer.Deserialize<ApiErrorResult<ApiError>>(billResult, jsonSerializerOptions);
                if (apiResult.Error.Code.Equals("InsufficientBalance", StringComparison.OrdinalIgnoreCase))
                {
                    return BadRequest(apiResult);
                }

                throw new NotImplementedException();
            }

            var saleInfo = JsonSerializer.Deserialize<TransactionObjectCreatedOutputModel<long>>(saleResult, jsonSerializerOptions);
            var orderInfo = JsonSerializer.Deserialize<TransactionObjectCreatedOutputModel<long>>(orderResult, jsonSerializerOptions);
            var billInfo = JsonSerializer.Deserialize<TransactionObjectCreatedOutputModel<long>>(billResult, jsonSerializerOptions);
            var links = new List<Link>
            {
                new Link
                {
                    Uri = saleInfo.Location,
                    Expires = saleInfo.Expires
                },
                new Link
                {
                    Uri = billInfo.Location,
                    Expires = billInfo.Expires
                },
                new Link
                {
                    Uri = orderInfo.Location,
                    Expires = orderInfo.Expires
                }
            };

            var resp = await client.PutAsync($"{Configuration["Coordinator"]}/coordinator/confirm",
                new StringContent(JsonSerializer.Serialize(new CoordinatorViewModel
                {
                    Links = links
                }), Encoding.UTF8, "application/json"));

            Logger.LogInformation("协调器返回结果: {code}", resp.StatusCode);

            return StatusCode(201);
        }
Example #24
0
 public RequestController(ClientFactory clientFactory)
 {
     _factory = clientFactory;
 }
        public static INotifySubscriberContract CreateClient(string serviceName)
        {
            ClientFactory factory = new ClientFactory();

            return(factory.CreateClient <NotifySubscriberClient, INotifySubscriberContract>(serviceName));
        }
Example #26
0
 /// <summary>
 /// Initialisiert eine neue Instanz der Server-Klasse unter verwendung des angegebenen Ports.
 /// </summary>
 /// <param name="port">Der zu verwendene Port.</param>
 public Server(int port)
 {
     this.Port = port;
     ClientFactory = new ClientFactory();
     this.AcceptNew = true;
 }
        public static INotifySubscriberContract CreateClient(Uri serviceUri, ServicePartitionKey servicePartitionKey)
        {
            ClientFactory factory = new ClientFactory();

            return(factory.CreateClient <NotifySubscriberClient, INotifySubscriberContract>(serviceUri, servicePartitionKey));
        }
Example #28
0
 public PartnersController()
 {
     _clientFactory = new ClientFactory();
 }
Example #29
0
        public async void ShouldReturnStacksAsString()
        {
            var result = await ExecuteAsync(ClientFactory.GetClient());

            Assert.NotNull(result);
        }
Example #30
0
 public void CreateTest()
 {
     var builder = new ClientFactory();
      var settings = new ClientSettings(ClientType.Legacy)
                 {
                    Name = "Client{ 1",
                    Path = @"\\test\path\"
                 };
      var instance = builder.Create(settings);
      Assert.IsNotNull(instance);
      Assert.AreEqual("Client 1", instance.Settings.Name);
 }
        public async void Test()
        {
            /*
             * contract Hashes{
             *
             *  function sha3Test(string _myvalue) returns (bytes32 val){
             *      return sha3(_myvalue);
             *  }
             *
             *  bytes32 public myHash;
             *
             *  function storeMyHash(bytes32 _myHash){
             *      myHash = _myHash;
             *  }
             * }
             */

            var text = "code monkeys are great";
            var hash = "0x1c21348936d43dc62d853ff6238cff94e361f8dcee9fde6fd5fbfed9ff663150";
            var web3 = new Web3(ClientFactory.GetClient());

            var sha3Hello = web3.Sha3(text);

            Assert.Equal(hash, "0x" + sha3Hello);

            var contractByteCode =
                "0x6060604052610154806100126000396000f360606040526000357c0100000000000000000000000000000000000000000000000000000000900480632bb49eb71461004f5780637c886096146100bd578063b6f61649146100d55761004d565b005b6100a36004808035906020019082018035906020019191908080601f0160208091040260200160405190810160405280939291908181526020018383808284378201915050505050509090919050506100fc565b604051808260001916815260200191505060405180910390f35b6100d3600480803590602001909190505061013d565b005b6100e2600480505061014b565b604051808260001916815260200191505060405180910390f35b600081604051808280519060200190808383829060006004602084601f0104600f02600301f15090500191505060405180910390209050610138565b919050565b806000600050819055505b50565b6000600050548156";

            var abi =
                @"[{""constant"":false,""inputs"":[{""name"":""_myvalue"",""type"":""string""}],""name"":""sha3Test"",""outputs"":[{""name"":""val"",""type"":""bytes32""}],""type"":""function""},{""constant"":false,""inputs"":[{""name"":""_myHash"",""type"":""bytes32""}],""name"":""storeMyHash"",""outputs"":[],""type"":""function""},{""constant"":true,""inputs"":[],""name"":""myHash"",""outputs"":[{""name"":"""",""type"":""bytes32""}],""type"":""function""}]";


            var gethTester = GethTesterFactory.GetLocal(web3);

            var receipt = await gethTester.DeployTestContractLocal(contractByteCode);

            //"0x350b79547251fdb18b64ec17cf3783e7d854bd30" (prev deployed contract)

            var contract = web3.Eth.GetContract(abi, receipt.ContractAddress);

            var sha3Function = contract.GetFunction("sha3Test");
            var result       = await sha3Function.CallAsync <byte[]>(text);

            Assert.Equal(hash, "0x" + result.ToHex());

            var storeMyHash = contract.GetFunction("storeMyHash");
            await gethTester.StartMining();

            await gethTester.UnlockAccount();

            var txn = await storeMyHash.SendTransactionAsync(gethTester.Account, hash.HexToByteArray());

            await gethTester.GetTransactionReceipt(txn);

            await gethTester.StopMining();


            var myHashFuction = contract.GetFunction("myHash");

            result = await myHashFuction.CallAsync <byte[]>();

            Assert.Equal(hash, "0x" + result.ToHex());
        }
Example #32
0
 public void CreateCollectionArgumentNullTest()
 {
     var builder = new ClientFactory();
      builder.CreateCollection((null));
 }
        public static IModelUpdateCommandEnqueuerContract CreateClient()
        {
            ClientFactory factory = new ClientFactory();

            return(factory.CreateClient <ModelUpdateCommandEnqueuerClient, IModelUpdateCommandEnqueuerContract>(microserviceName));
        }
Example #34
0
 public void CreateNameEmptyTest()
 {
     var builder = new ClientFactory();
      builder.Create(new ClientSettings(ClientType.Legacy));
 }
Example #35
0
 public void CreateArgumentNullTest()
 {
    var builder = new ClientFactory();
    Assert.Throws<ArgumentNullException>(() => builder.Create(null));
 }
Example #36
0
 public static bool SetClientEndpointAddress(string clientEndpointName, string address)
 {
     return(ClientFactory.SetClientEndpointAddress(_configDictionary, clientEndpointName, address));
 }
Example #37
0
 public void CreateNameFailedCleanupTest()
 {
    var builder = new ClientFactory();
    var invalidChars = System.IO.Path.GetInvalidFileNameChars();
    Assert.Throws<ArgumentException>(() => builder.Create(new ClientSettings(ClientType.Legacy)
                                                          {
                                                             Name = " " + invalidChars[0] + invalidChars[1] + " ",
                                                             Path = @"\\test\path\"
                                                          }));
 }
Example #38
0
 public static Web3.Web3 GetWeb3Managed()
 {
     return(new Web3.Web3(AccountFactory.GetManagedAccount(), ClientFactory.GetClient()));
 }
Example #39
0
 public void Test()
 {
     ClientFactory.Verify(f => f.Create(), Times.Exactly(2));
 }
 public void VerifyProductInfoHeaderValueEquality()
 {
     ClientFactory factory = new ClientFactory();
     factory.AddUserAgent("test1", "123");
     factory.AddUserAgent("test2", "123");
     factory.AddUserAgent("test1", "123");
     factory.AddUserAgent("test1", "456");
     factory.AddUserAgent("test3");
     factory.AddUserAgent("tesT3");
     
     Assert.Equal(4, factory.UserAgents.Count);
     Assert.True(factory.UserAgents.Any(u => u.Product.Name == "test1" && u.Product.Version == "123"));
     Assert.True(factory.UserAgents.Any(u => u.Product.Name == "test2" && u.Product.Version == "123"));
     Assert.True(factory.UserAgents.Any(u => u.Product.Name == "test1" && u.Product.Version == "456"));
     Assert.True(factory.UserAgents.Any(u => u.Product.Name == "test3" && u.Product.Version == null));
 }
Example #41
0
 protected RPCRequestTester()
 {
     Settings        = new TestSettings();
     Client          = ClientFactory.GetClient(Settings);
     StreamingClient = ClientFactory.GetStreamingClient(Settings);
 }
        public async void ShouldRetrieveBlockNumberBiggerThanZero()
        {
            var blockNumber = await ExecuteAsync(ClientFactory.GetClient());

            Assert.True(blockNumber.Value > 0);
        }
        public async Task <WriteResponse> UpsertAsync <T>(T item, [CallerMemberName] string callerName = "", [CallerFilePath] string path = "", [CallerLineNumber] int lineNumber = 0) where T : IViewModel
        {
            var container = await ClientFactory.GetContainerAsync(Settings).ConfigureAwait(false);

            return(await UpsertAsync(container, item, callerName, path, lineNumber).ConfigureAwait(false));
        }
Example #44
0
 public void Create_FahClientFactoryNull_Test()
 {
    var builder = new ClientFactory();
    var settings = new ClientSettings(ClientType.FahClient)
    {
       Name = "FahClient",
       Server = "192.168.100.200"
    };
    var instance = builder.Create(settings);
    Assert.IsNull(instance);
 }
Example #45
0
 public MyProject(ClientFactory factory)
 {
     _factory = factory;
 }
        public static IModelUpdateCommandEnqueuerContract CreateClient(Uri serviceUri, ServicePartitionKey servicePartitionKey)
        {
            ClientFactory factory = new ClientFactory();

            return(factory.CreateClient <ModelUpdateCommandEnqueuerClient, IModelUpdateCommandEnqueuerContract>(serviceUri, servicePartitionKey));
        }
Example #47
0
 public void Test()
 {
     ClientFactory.Verify(f => f.Create(), Times.Once());
 }
Example #48
0
 public void CreatePathEmptyTest()
 {
    var builder = new ClientFactory();
    Assert.Throws<ArgumentException>(() => builder.Create(new ClientSettings(ClientType.Legacy) { Name = "Client 1" }));
 }
        public static IOutageAccessContract CreateClient()
        {
            ClientFactory factory = new ClientFactory();

            return(factory.CreateClient <OutageAccessClient, IOutageAccessContract>(microserviceName));
        }
Example #50
0
 public void CreateTest()
 {
    var legacyClientFactory = MockRepository.GenerateStub<ILegacyClientFactory>();
    legacyClientFactory.Stub(x => x.Create()).Return(new LegacyClient());
    var builder = new ClientFactory { LegacyClientFactory = legacyClientFactory };
    var settings = new ClientSettings(ClientType.Legacy)
                   {
                      Name = "Client{ 1",
                      Path = @"\\test\path\"
                   };
    var instance = builder.Create(settings);
    Assert.IsNotNull(instance);
    Assert.AreEqual("Client 1", instance.Settings.Name);
 }
        public static IOutageAccessContract CreateClient(Uri serviceUri, ServicePartitionKey servicePartitionKey)
        {
            ClientFactory factory = new ClientFactory();

            return(factory.CreateClient <OutageAccessClient, IOutageAccessContract>(serviceUri, servicePartitionKey));
        }
Example #52
0
        private String RequestAccessThroughPrivateUSS(string token, string client, string ip, CancellationTokenSource cancelToken)
        {
            IPrivateUserSessionService channel = null;
            try
            {
                var factory = new ClientFactory<IPrivateUserSessionService>();
                channel = factory.CreateLocalTcpConnection(9751, "MPExtended/UserSessionServicePrivate");

                // request access
                bool result = channel.RequestAccess(token, client, ip, Configuration.Authentication.Users.Select(x => x.Username).ToList());
                String selectedUser = null;

                if (result)
                {
                    while (!cancelToken.IsCancellationRequested)
                    {
                        WebAccessRequestResponse response = channel.GetAccessRequestStatus(token);
                        if (response.UserHasResponded)
                        {
                            selectedUser = response.IsAllowed ? response.Username : null;
                            break;
                        }
                        Thread.Sleep(500);
                    }
                }

                if (cancelToken.IsCancellationRequested)
                {
                    channel.CancelAccessRequest(token);
                }

                // close channel
                (channel as ICommunicationObject).Close();
                return selectedUser;
            }
            catch (Exception ex)
            {
                Log.Error(String.Format("Failed to request access for client {0} at {1} through USS", client, ip), ex);
                return ERROR;
            }
        }
        public async Task <T> ExecuteAsync <T>(IUnionPayRequest <T> request) where T : UnionPayResponse
        {
            var version = string.Empty;

            if (!string.IsNullOrEmpty(request.GetApiVersion()))
            {
                version = request.GetApiVersion();
            }
            else
            {
                version = Options.Version;
            }

            var merId = Options.MerId;

            if (Options.TestMode && (request is UnionPayForm05_7_FileTransferRequest || request is UnionPayForm_6_6_FileTransferRequest))
            {
                merId = "700000000000001";
            }

            var txtParams = new UnionPayDictionary(request.GetParameters())
            {
                { VERSION, version },
                { ENCODING, Options.Encoding },
                { SIGNMETHOD, Options.SignMethod },
                { ACCESSTYPE, Options.AccessType },
                { MERID, merId },
            };

            if (request.HasEncryptCertId())
            {
                txtParams.Add(ENCRYPTCERTID, Options.EncryptCertificate.certId);
            }

            UnionPaySignature.Sign(txtParams, Options.SignCertificate.certId, Options.SignCertificate.key, Options.SecureKey);

            var query = UnionPayUtility.BuildQuery(txtParams);

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

            using (var client = ClientFactory.CreateClient(UnionPayOptions.DefaultClientName))
            {
                var body = await HttpClientUtility.DoPostAsync(client, request.GetRequestUrl(Options.TestMode), query);

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

                var dic = ParseQueryString(body);

                if (string.IsNullOrEmpty(body))
                {
                    throw new Exception("sign check fail: Body is Empty!");
                }

                var ifValidateCNName = !Options.TestMode;
                if (!UnionPaySignature.Validate(dic, Options.RootCertificate.cert, Options.MiddleCertificate.cert, Options.SecureKey, ifValidateCNName))
                {
                    throw new Exception("sign check fail: check Sign and Data Fail!");
                }

                var parser = new UnionPayDictionaryParser <T>();
                var rsp    = parser.Parse(dic);
                rsp.Body = body;
                return(rsp);
            }
        }