コード例 #1
0
ファイル: Program.cs プロジェクト: Yuanxiangz/WorkSpace
        static void Main(string[] args)
        {
            ChannelFactory<IService> channelFactory = null;
            try
            {
                channelFactory = new ChannelFactory<IService>("Endpoint1");
                ThreadPool.QueueUserWorkItem((o) =>
                    {
                        for (int i = 1; i <= 1000; i++)
                        {
                            Console.WriteLine("{0}: invocate service! thread 1", i);
                            Console.WriteLine(channelFactory.CreateChannel().DoReturn());
                            //Thread.Sleep(1000);
                        }
                    });

                ThreadPool.QueueUserWorkItem((o) =>
                {
                    for (int i = 1; i <= 1000; i++)
                    {
                        Console.WriteLine("{0}: invocate service! thread 2", i);
                        Console.WriteLine(channelFactory.CreateChannel().DoReturn());
                        //Thread.Sleep(1000);
                    }
                });
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                channelFactory.Close();
            }

            Console.ReadKey();
        }
コード例 #2
0
ファイル: Program.cs プロジェクト: huoxudong125/WCF-Demo
        static void Main(string[] args)
        {
            EndpointAddress address = new EndpointAddress("http://127.0.0.1:3721/calculatorservice");
            using (ChannelFactory<ICalculator> channelFactory = new ChannelFactory<ICalculator>(new SimpleDatagramBinding(), address))
            {
                //创建第一个服务代理
                ICalculator proxy = channelFactory.CreateChannel();
                proxy.Add(1, 2);
                Console.WriteLine("Done");
                proxy.Add(1, 2);
                Console.WriteLine("Done");
                (proxy as ICommunicationObject).Close();

                //创建第二个服务代理
                proxy = channelFactory.CreateChannel();
                proxy.Add(1, 2);
                Console.WriteLine("Done");
                proxy.Add(1, 2);
                Console.WriteLine("Done");
                (proxy as ICommunicationObject).Close();

                channelFactory.Close();
            }
            Console.Read();
        }
コード例 #3
0
    public static void MultipleClientsNonConcurrentNetTcpClientConnection()
    {
        string testString = new string('a', 3000);
        var    host       = CreateWebHostBuilder(new string[0]).Build();

        using (host)
        {
            host.Start();
            var binding = new System.ServiceModel.NetTcpBinding
            {
                TransferMode = System.ServiceModel.TransferMode.Streamed
            };
            var factory = new System.ServiceModel.ChannelFactory <ClientContract.ITestService>(binding,
                                                                                               new System.ServiceModel.EndpointAddress(new Uri("net.tcp://localhost:8808/nettcp.svc")));
            var channel = factory.CreateChannel();
            ((IChannel)channel).Open();
            var result = channel.EchoString(testString);
            ((IChannel)channel).Close();
            Assert.Equal(testString, result);
            channel = factory.CreateChannel();
            ((IChannel)channel).Open();
            result = channel.EchoString(testString);
            ((IChannel)channel).Close();
            Assert.Equal(testString, result);
        }
    }
コード例 #4
0
ファイル: Program.cs プロジェクト: kinpauln/RoadLamps
        private static void Test1()
        {
            try
            {
                Random rd = new Random();
                using (ChannelFactory<RoadLamps.Service.Old.IEquipmentService> channel = new ChannelFactory<RoadLamps.Service.Old.IEquipmentService>("CalculatorService"))
                {
                    for (int i = 0; i < 5; i++)
                    {
                        ThreadPool.QueueUserWorkItem(
                            delegate
                            {
                                RoadLamps.Service.Old.IEquipmentService ic = channel.CreateChannel();
                                using (ic as IDisposable)
                                {
                                    double x = 100 * rd.NextDouble();
                                    double y = 100 * rd.NextDouble();
                                    ic.Add(x, y);
                                    Console.WriteLine("第" + i.ToString() + "次请求已发送...");
                                }

                            });
                    }
                    RoadLamps.Service.Old.IEquipmentService ic2 = channel.CreateChannel();
                    ic2.CreateFile();
                    Console.WriteLine("请求发送完毕...");
                    Console.Read();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.StackTrace);
                Console.Read();
            }
        }
コード例 #5
0
ファイル: Program.cs プロジェクト: rdzzg/LearnningDemo
        public static void InvokeThenTerminateSession()
        {
            ChannelFactory<ICalculator> calculatorChannelFactory = new ChannelFactory<ICalculator>("httpEndpoint");
            Console.WriteLine("Create a calculator proxy: proxy1");
            ICalculator proxy1 = calculatorChannelFactory.CreateChannel();
            Console.WriteLine("Invocate  proxy1.Adds(1)");
            proxy1.Adds(1);
            Console.WriteLine("Invocate  proxy1.Adds(2)");
            proxy1.Adds(2);
            Console.WriteLine("The result return via proxy1.GetResult() is : {0}", proxy1.GetResult());
            Console.WriteLine("Invocate  proxy1.Adds(1)");
            try
            {
                proxy1.Adds(1);
            }
            catch (Exception ex)
            {
                Console.WriteLine("It is fail to invocate the Add after terminating session because \"{0}\"", ex.Message);
            }

            Console.WriteLine("Create a calculator proxy: proxy2");
            ICalculator proxy2= calculatorChannelFactory.CreateChannel();
            Console.WriteLine("Invocate  proxy2.Adds(1)");
            proxy2.Adds(1);
            Console.WriteLine("Invocate  proxy2.Adds(2)");
            proxy2.Adds(2);
            Console.WriteLine("The result return via proxy2.GetResult() is : {0}", proxy2.GetResult());

            Console.Read();
        }
コード例 #6
0
    public static void MultipleClientsUsingPooledSocket()
    {
        var host = CreateWebHostBuilder(new string[0]).Build();

        using (host)
        {
            host.Start();
            var binding = new System.ServiceModel.NetTcpBinding()
            {
                OpenTimeout    = TimeSpan.FromMinutes(20),
                CloseTimeout   = TimeSpan.FromMinutes(20),
                SendTimeout    = TimeSpan.FromMinutes(20),
                ReceiveTimeout = TimeSpan.FromMinutes(20)
            };
            var factory = new System.ServiceModel.ChannelFactory <ClientContract.ITestService>(binding,
                                                                                               new System.ServiceModel.EndpointAddress(new Uri("net.tcp://localhost:8808/nettcp.svc")));
            var channel = factory.CreateChannel();
            ((IChannel)channel).Open();
            var clientIpEndpoint = channel.GetClientIpEndpoint();
            ((IChannel)channel).Close();
            for (int i = 0; i < 10; i++)
            {
                channel = factory.CreateChannel();
                ((IChannel)channel).Open();
                var clientIpEndpoint2 = channel.GetClientIpEndpoint();
                ((IChannel)channel).Close();
                Assert.Equal(clientIpEndpoint, clientIpEndpoint2);
            }
        }
    }
コード例 #7
0
ファイル: Program.cs プロジェクト: huoxudong125/WCF-Demo
 static void Main(string[] args)
 {
     using (ChannelFactory<ICalculator> channelFactory = new ChannelFactory<ICalculator>("calculatorservice"))
     {
         ICalculator serviceProxy1 = channelFactory.CreateChannel();
         serviceProxy1.Add(1, 2);
         ICalculator serviceProxy2 = channelFactory.CreateChannel();
         serviceProxy2.Add(1, 2);
     }
     Console.Read();
 }
コード例 #8
0
ファイル: Client.cs プロジェクト: ssickles/archive
        static void Main(string[] args)
        {
            Console.WriteLine(
                "Press <enter> to open a channel and send a request.");

            Console.ReadLine();
            
            MessageHeader shareableInstanceContextHeader = MessageHeader.CreateHeader(
                    CustomHeader.HeaderName,
                    CustomHeader.HeaderNamespace,
                    Guid.NewGuid().ToString());

            ChannelFactory<IEchoService> channelFactory =
                new ChannelFactory<IEchoService>("echoservice");
            
            IEchoService proxy = channelFactory.CreateChannel();


            using (new OperationContextScope((IClientChannel)proxy))
            {
                OperationContext.Current.OutgoingMessageHeaders.Add(shareableInstanceContextHeader);
                Console.ForegroundColor = ConsoleColor.Green;
                Console.WriteLine("Service returned: " + proxy.Echo("Apple"));
                Console.ForegroundColor = ConsoleColor.Gray;
            }

            ((IChannel)proxy).Close();

            Console.WriteLine("Channel No 1 closed.");

            Console.WriteLine(
                "Press <ENTER> to send another request from a different channel " + 
                "to the same instance. ");            

            Console.ReadLine();

            proxy = channelFactory.CreateChannel();

            using (new OperationContextScope((IClientChannel)proxy))
            {
                OperationContext.Current.OutgoingMessageHeaders.Add(shareableInstanceContextHeader);
                Console.ForegroundColor = ConsoleColor.Green;
                Console.WriteLine("Service returned: " + proxy.Echo("Apple"));
                Console.ForegroundColor = ConsoleColor.Gray;
            }
            
            ((IChannel)proxy).Close();

            Console.WriteLine("Channel No 2 closed.");
		
            Console.WriteLine("Press <ENTER> to complete test.");
            Console.ReadLine();
        }
コード例 #9
0
        static int Main()
        {
            const string name = "ShakerService";
            const string address = "http://localhost:5110";

            using( var channel = new ChannelFactory< RecipeBookContract >( name ) )
            {
                var recipes = channel.CreateChannel( new EndpointAddress( address ) );
                recipes.Add(
                    new DrinkDto{ Name = "G&T", Method = "Mix with ice and lime" },
                    new[] {
                        new IngredientDto{ Name = "Gin",
                                           Amount = IngredientDto.Measurement.Measure,
                                           Qty = 2 },
                        new IngredientDto{ Name = "Tonic Water",
                                           Amount = IngredientDto.Measurement.Fill,
                                           Qty = 1 }
                    } );
                foreach( var d in recipes.AllDrinks() )
                {
                    Console.WriteLine( d.Name );
                }
                Console.WriteLine( "Press [Enter] to exit" );
                Console.ReadLine();

                return 0;
            }
        }
コード例 #10
0
ファイル: Client.cs プロジェクト: novakvova/WCFLesson1
        static void Main(string[] args)
        {
            Console.Title = "CLIENT";

            // Указание, где ожидать входящие сообщения.
            Uri address = new Uri("http://localhost:4000/IContract");  // ADDRESS.   (A)

            // Указание, как обмениваться сообщениями.
            BasicHttpBinding binding = new BasicHttpBinding();         // BINDING.   (B)

            // Создание Конечной Точки.
            EndpointAddress endpoint = new EndpointAddress(address);

            // Создание фабрики каналов.
            ChannelFactory<IContract> factory = new ChannelFactory<IContract>(binding, endpoint);  // CONTRACT.  (C) 

            // Использование factory для создания канала (прокси).
            IContract channel = factory.CreateChannel();
            
            // Использование канала для отправки сообщения получателю.
            channel.Say("Hello WCF!");// сложный механизм

            // Задержка.
            Console.ReadKey();
        }
コード例 #11
0
ファイル: Orders.cs プロジェクト: jonteho/ticketing-office
        public IEnumerable<Order> GetCustomersOrders(CrmService.Contracts.Customer customer)
        {
            var channelFactory = new ChannelFactory<CrmService.Contracts.ICrmService>("CrmEP");

            CrmService.Contracts.ICrmService proxy = channelFactory.CreateChannel();
            return proxy.GetCustomerOrders(customer.ID, null, null);
        }
コード例 #12
0
        static void Main(string[] args)
        {
            try
            {
                using (var cf = new ChannelFactory<IRestService>(new WebHttpBinding(), RestUri))
                {
                    cf.Endpoint.Behaviors.Add(new WebHttpBehavior());
                    var channel = cf.CreateChannel();

                    Console.WriteLine("Calling Multiply: ");
                    var result = channel.Multiply(6, 23);
                    Console.WriteLine("6*23 = {0}", result);

                    Console.WriteLine("");

                    Console.WriteLine("Calling CreateNewUser (POST): ");
                    var result1 = channel.CreateNewUser("foobar", "verystrongpasswortnot");
                    Console.WriteLine("User created? {0}", result1);
                    Console.WriteLine("");
                }

                Console.WriteLine("Press <ENTER> to terminate");
                Console.ReadLine();
            }
            catch (CommunicationException e)
            {
                Console.WriteLine("An exception occurred: {0}", e.Message);
            }
        }
コード例 #13
0
        public void ServerAncClientExceptionsEndpointBehavior()
        {
            var hook = new ExceptionsEndpointBehaviour();
            var address = @"net.pipe://127.0.0.1/test" + this.GetType().Name + "_" + MethodBase.GetCurrentMethod().Name;
            var serv = new ExceptionService();
            using (var host = new ServiceHost(serv, new Uri[] { new Uri(address), }))
            {
                var b = new NetNamedPipeBinding();
                var serverEndpoint = host.AddServiceEndpoint(typeof(IExceptionService), b, address);
                serverEndpoint.Behaviors.Add(hook);

                host.Open();

                var f = new ChannelFactory<IExceptionService>(b);
                f.Endpoint.Behaviors.Add(hook);

                var c = f.CreateChannel(new EndpointAddress(address));

                try
                {
                    c.DoException("message");
                }
                catch (InvalidOperationException ex)
                {
                    StringAssert.AreEqualIgnoringCase("message", ex.Message);
                }
                host.Abort();
            }
        }
コード例 #14
0
        public void Submit(Order order)
        {
            Console.WriteLine("Begin to process the order of the order No.: {0}", order.OrderNo);
            FaultException exception = null;
            if (order.OrderDate < DateTime.Now) {
                exception = new FaultException(new FaultReason("The order has expried"), new FaultCode("sender"));
                Console.WriteLine("It's fail to process the order.\n\tOrder No.: {0}\n\tReason:{1}", order.OrderNo, "The order has expried");
            } else {
                Console.WriteLine("It's successful to process the order.\n\tOrder No.: {0}", order.OrderNo);
            }
            NetMsmqBinding binding = new NetMsmqBinding();
            binding.ExactlyOnce = false;
            binding.Security.Transport.MsmqAuthenticationMode = MsmqAuthenticationMode.None;
            binding.Security.Transport.MsmqProtectionLevel = ProtectionLevel.None;

            ChannelFactory<IOrderRessponse> channelFactory = new ChannelFactory<IOrderRessponse>(binding);
            OrderResponseContext responseContext = OrderResponseContext.Current;

            IOrderRessponse channel = channelFactory.CreateChannel(new EndpointAddress(responseContext.ResponseAddress));

            using (OperationContextScope contextScope = new OperationContextScope(channel as IContextChannel)) {
                channel.SubmitOrderResponse(order.OrderNo, exception);
            }
            Console.Read();
        }
コード例 #15
0
        static void Main(string[] args)
        {
            var cfV2 = new ChannelFactory<IComplexNumber>("secondVersionEndUsers");
            var channelV2 = cfV2.CreateChannel();

            var z1 = new ComplexNumber();
            var z2 = new ComplexNumber();

            z1.Real = 1D;
            z1.Imaginary = 2D;

            z2.Real = 2D;
            z2.Imaginary = 1D;

            Console.WriteLine("*** Service Versioning: end-users of the second version ***\n");
            Console.WriteLine("\nPlease hit any key to run OR enter 'exit' to terminate.");
            string command = Console.ReadLine();

            while (command != "exit")
            {
                Console.WriteLine("Please hit any key to simulate secondVersionEndUsers: ");
                Console.ReadLine();

                using (new OperationContextScope((IContextChannel)channelV2))
                {
                    OperationContext.Current.OutgoingMessageHeaders.Add(MessageHeader.CreateHeader("Version", "http://custom/namespace", "v2.0"));
                    ComplexNumberArithmetics(channelV2, z1, z2);
                }

                Console.WriteLine("\nPlease hit any key to re-run OR enter 'exit' to terminate.");
                command = Console.ReadLine();
            }

           ((IClientChannel)channelV2).Close();
        }
コード例 #16
0
        public Client(string serverAddress)
        {
            if (EventManager.Instance.Protocol == EventManager.XML_RPC)
            {
                address = serverAddress;
                Uri eventManagerAddress;
                if (EventManager.singleMachineDebug)
                    //For test on a single machine
                    eventManagerAddress = new Uri("http://" + serverAddress + "/EventManager");
                else
                    eventManagerAddress = new Uri("http://" + serverAddress + ":8000/xmlrpc/EventManager");

                ChannelFactory<IEMServiceWCF_XML_RPC> eventManagerFactory =
                    new ChannelFactory<IEMServiceWCF_XML_RPC>(
                        new WebHttpBinding(WebHttpSecurityMode.None),
                        new EndpointAddress(eventManagerAddress));
                eventManagerFactory.Endpoint.EndpointBehaviors.Add(new Microsoft.Samples.XmlRpc.XmlRpcEndpointBehavior());

                eManagerWCF_XML_RPC = eventManagerFactory.CreateChannel();
            }
            else if (EventManager.Instance.Protocol == EventManager.REMOTING)
            {
                eManagerREMOTING = (EMServiceRemoting)Activator.GetObject(typeof(EMServiceRemoting), "http://" + serverAddress + ":8080/EventManager/RemotingService");
            }
        }
コード例 #17
0
 public static void Exit(string target, int timeout = 15)
 {
     var factory = new ChannelFactory<ISignalListener>(new NetNamedPipeBinding().SetTimeout(timeout),
                                                 new EndpointAddress("net.pipe://localhost/" + target));
       var client = factory.CreateChannel();
       client.Exit();
 }
 public void test_account_manager_as_service()
 {
     ChannelFactory<IAccountService> channelFactory = new ChannelFactory<IAccountService>("");
     IAccountService proxy = channelFactory.CreateChannel();
     (proxy as ICommunicationObject).Open();
     channelFactory.Close();
 }
コード例 #19
0
ファイル: Client.cs プロジェクト: novakvova/WCFLesson1
        static void Main(string[] args)
        {
            Console.Title = "CLIENT";

            // Указание, где ожидать входящие сообщения.
            Uri address = new Uri("http://localhost:4000/IContract");

            // Указание, как обмениваться сообщениями.
            BasicHttpBinding binding = new BasicHttpBinding();

            // Создание Конечной Точки. 
            EndpointAddress endpoint = new EndpointAddress(address);

            // Создание фабрики каналов.
            ChannelFactory<IContract> factory = new ChannelFactory<IContract>(binding, endpoint);

            // Использование factory для создания канала (прокси).
            IContract channel = factory.CreateChannel();
            
            // Использование канала для отправки сообщения получателю и приема ответа.
            string response = channel.Say("Hello WCF!");

            Console.WriteLine(response);

            // Задержка.
            Console.ReadKey();
        }
コード例 #20
0
        public CoreServiceProvider()
        {
            var binding = new BasicHttpBinding
            {
                MaxReceivedMessageSize = 10485760,
                ReaderQuotas = new XmlDictionaryReaderQuotas
                {
                    MaxStringContentLength = 10485760,
                    MaxArrayLength = 10485760
                },
                Security = new BasicHttpSecurity
                {
                    Mode = BasicHttpSecurityMode.TransportCredentialOnly,
                    Transport = new HttpTransportSecurity
                    {
                        ClientCredentialType = HttpClientCredentialType.Windows
                    }
                }
            };

            string coreServiceUrl = ConfigurationManager.AppSettings[Constants.TRIDION_CME_URL] + "/webservices/CoreService2013.svc/basicHttp";
            Console.WriteLine("Connect to CoreService " + coreServiceUrl);

            EndpointAddress endpoint = new EndpointAddress(coreServiceUrl);
            factory = new ChannelFactory<ICoreService>(binding, endpoint);

            string userName = ConfigurationManager.AppSettings[Constants.USER_NAME];
            string password = ConfigurationManager.AppSettings[Constants.PASSWORD];
            factory.Credentials.Windows.ClientCredential = new NetworkCredential(userName, password);

            Client = factory.CreateChannel();

            UserData user = Client.GetCurrentUser();
            Console.WriteLine("Connected as {0} ({1})", user.Description, user.Title);
        }
コード例 #21
0
        public IEnumerable<RepositoryInformation> GetRepositoryInformation(string queryString)
        {
            if(_repositoryNames != null)
                return _repositoryNames; //for now, there's no way to get an updated list except by making a new client

            const string genericUrl = "scheme://path?";
            var finalUrl = string.IsNullOrEmpty(queryString)
                               ? queryString
                               : genericUrl + queryString;
            var binding = new NetTcpBinding
            {
                Security = {Mode = SecurityMode.None}
            };

            var factory = new ChannelFactory<IChorusHubService>(binding, _chorusHubServerInfo.ServiceUri);

            var channel = factory.CreateChannel();
            try
            {
                var jsonStrings = channel.GetRepositoryInformation(finalUrl);
                _repositoryNames = ImitationHubJSONService.ParseJsonStringsToChorusHubRepoInfos(jsonStrings);
            }
            finally
            {
                var comChannel = (ICommunicationObject)channel;
                if (comChannel.State != CommunicationState.Faulted)
                {
                    comChannel.Close();
                }
            }
            return _repositoryNames;
        }
コード例 #22
0
ファイル: Program.cs プロジェクト: kmvi/JsonRpc.ServiceModel
        static void ChannelFactoryExample(string baseUri)
        {
            var factory = new ChannelFactory<ISimpleService>(
                new JsonRpcHttpBinding(),
                new EndpointAddress(baseUri + "/json-rpc"));

            factory.Endpoint.Behaviors.Add(new JsonRpcBehavior());

            var client = factory.CreateChannel();

            Console.WriteLine("SimpleMethod(\"World\"): " + client.SimpleMethod("World"));
            Console.WriteLine("Add(42, 24): " + client.Add(42, 24).ToString());
            Console.WriteLine("GetComplexType(3.14): " + client.GetComplexType(3.14).ToString());

            Console.Write("Call VoidMethod()... ");
            client.VoidMethod();
            Console.WriteLine("success");

            Console.WriteLine("ComplexArg(arg): " +
                client.ComplexArg(new ComplexType { Name = "1234", BirthDate = DateTime.Now }));

            try {
                var result = client.GotException();
            } catch (JsonRpcException e) {
                Console.WriteLine("GotException(): " + e.ToString());
            }
        }
コード例 #23
0
ファイル: Program.cs プロジェクト: ufo20020427/FileUpload
        static void Test()
        {
            try
            {
                NetTcpBinding binding = new NetTcpBinding();
                binding.TransferMode = TransferMode.Streamed;
                binding.SendTimeout = new TimeSpan(0, 0, 2);

                channelFactory = new ChannelFactory<IFileUpload>(binding, ClientConfig.WCFAddress);

                _proxy = channelFactory.CreateChannel();

                (_proxy as ICommunicationObject).Open();

                Console.WriteLine("主方法开始执行:" + DateTime.Now.ToString());
                _proxy.BeginAdd(1, 2, EndAdd, null);
                Console.WriteLine("主方法结束:" + DateTime.Now.ToString());

            }
            catch (Exception ex)
            {
                Tools.LogWrite(ex.ToString());
                Console.WriteLine(ex.ToString());
            }
        }
コード例 #24
0
        public static void Send(Pager model)
        {
            if (model.To == null || string.IsNullOrWhiteSpace(model.Message)) return;

            using (model.Modifier(x => x.Message))
            {

                Message message = new Message
                {
                    CreatedTime   = DateTime.Now,
                    From          = From,
                    To            = model.To,
                    ContentAsText = model.Message
                };

                model.Message = string.Empty;
                model.History.Add(message)  ;

                m_history.Add(message);

                using (var factory = new ChannelFactory<IMessageHost>(new BasicHttpBinding(), message.To.Uri))
                {
                     factory.Open();
             					 factory.CreateChannel().Send(new Request<Message>(message));
                }

            }
        }
コード例 #25
0
ファイル: LucidClient.cs プロジェクト: mkonicek/raytracer
        public void Connect(string endPointAddress)
        {
            if (this._lucidServer != null)
            {
                Disconnect();
            }

            EndpointAddress serverEndpointAddress;
            try
            {
                serverEndpointAddress = new EndpointAddress(endPointAddress);
            }
            catch
            {
                // bad url
                throw new Exception("Bad server URL: " + endPointAddress);
            }
            Binding binding = new NetTcpBinding(SecurityMode.None, true);
            binding.ReceiveTimeout = TimeSpan.FromSeconds(10);
            binding.SendTimeout = TimeSpan.FromSeconds(10);
            binding.OpenTimeout = TimeSpan.FromSeconds(10);
            var factory = new ChannelFactory<ILucidService>(binding, serverEndpointAddress);

            this._lucidServer = factory.CreateChannel();
            // let server know we are available
            this._lucidServer.RegisterClient();

            Inv.Log.Log.WriteMessage("Connected to server " + endPointAddress);
        }
コード例 #26
0
ファイル: FS2Factory.cs プロジェクト: saeednazari/Rubezh
		IFS2Contract DoCreate(string serverAddress)
		{
			if (serverAddress.StartsWith("net.pipe:"))
			{
				if (!FS2LoadHelper.Load())
					BalloonHelper.ShowFromFiresec("Не удается соединиться с агентом 2");
			}

			var binding = BindingHelper.CreateBindingFromAddress(serverAddress);

			var endpointAddress = new EndpointAddress(new Uri(serverAddress));
			ChannelFactory = new ChannelFactory<IFS2Contract>(binding, endpointAddress);

			foreach (OperationDescription operationDescription in ChannelFactory.Endpoint.Contract.Operations)
			{
				DataContractSerializerOperationBehavior dataContractSerializerOperationBehavior = operationDescription.Behaviors.Find<DataContractSerializerOperationBehavior>() as DataContractSerializerOperationBehavior;
				if (dataContractSerializerOperationBehavior != null)
					dataContractSerializerOperationBehavior.MaxItemsInObjectGraph = Int32.MaxValue;
			}

			ChannelFactory.Open();

			IFS2Contract firesecService = ChannelFactory.CreateChannel();
			(firesecService as IContextChannel).OperationTimeout = TimeSpan.FromMinutes(10);
			return firesecService;
		}
コード例 #27
0
ファイル: Program.cs プロジェクト: GusLab/WCFSamples
        static void Main(string[] args)
        {
            string baseAddress = "http://" + Environment.MachineName + ":8000/Service";

            foreach (Type badServiceType in new Type[] { typeof(BadService1_NoDefaultCtor), typeof(BadService2_RefParameter) })
            {
                try
                {
                    new PocoServiceHost(badServiceType, new Uri(baseAddress)).Open();
                    Console.WriteLine("This line should not be reached");
                }
                catch (InvalidOperationException e)
                {
                    Console.WriteLine("Caught expected exception for service {0}: {1}", badServiceType.Name, e.Message);
                }
            }

            PocoServiceHost host = new PocoServiceHost(typeof(Service), new Uri(baseAddress));
            host.Open();

            ChannelFactory<ITest> factory = new ChannelFactory<ITest>(new BasicHttpBinding(), new EndpointAddress(baseAddress));
            ITest proxy = factory.CreateChannel();

            Console.WriteLine(proxy.Add(4, 5));
            Console.WriteLine(proxy.Distance(new Point { X = 0, Y = 0 }, new Point { X = 3, Y = 4 }));

            Console.WriteLine("Press ENTER to close");
            Console.ReadLine();
            host.Close();
        }
コード例 #28
0
ファイル: WCFClient.cs プロジェクト: MaHuJa/withSIX.Desktop
        public WCFClient(IEventAggregator eventBus) {
            _eventBus = eventBus;
            _pipeFactory = new ChannelFactory<IUpdaterWCF>(new NetNamedPipeBinding(), new EndpointAddress(
                "net.pipe://localhost/UpdaterWCF_Pipe"));

            _pipeProxy = _pipeFactory.CreateChannel();
        }
コード例 #29
0
ファイル: Client.cs プロジェクト: kimpers/school_work
 public Client(String URL)
 {
     BasicHttpBinding myBinding = new BasicHttpBinding();
     EndpointAddress  myEndpoint = new EndpointAddress(URL);
     myChannelFactory = new ChannelFactory<Server.IServerService>(myBinding, myEndpoint);
     comInterface = myChannelFactory.CreateChannel();
 }
コード例 #30
0
ファイル: Form1.cs プロジェクト: kirigishi123/try_samples
        private void StartDownload()
        {
            new Thread(delegate()
            {
                bool retry = false;
                int count = 0;

                do {
                    retry = false;
                    try {
                        NetNamedPipeBinding binding = new NetNamedPipeBinding(NetNamedPipeSecurityMode.None);
                        EndpointAddress address = new EndpointAddress("net.pipe://localhost/download");
                        using (ChannelFactory<IDownloadManager> factory = new ChannelFactory<IDownloadManager>(binding, address))
                        {
                            IDownloadManager dm = factory.CreateChannel();

                            if (dm != null)
                            {
                                string msg = dm.CopyFile("test file");
                                MessageBox.Show(msg);
                            }

                            factory.Close();
                        }
                    }
                    catch (CommunicationException)
                    {
                        retry = (count++ < 30);
                        Thread.Sleep(1000);
                    }
                } while(retry);

            }).Start();
        }
コード例 #31
0
        public void TestMethod1()
        {
            var token = GetToken();

            ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;

            var binding = new WebHttpBinding
            {
                Security =
                {
                    Mode = WebHttpSecurityMode.Transport,
                    Transport = {ClientCredentialType = HttpClientCredentialType.None}
                }
            };

            using (var factory = new ChannelFactory<IThingsService>(binding, "https://localhost:1234/things"))
            {
                factory.Endpoint.Behaviors.Add(new WebHttpBehavior());
                var channel = factory.CreateChannel();

                using (new OperationContextScope((IContextChannel)channel))
                {
                    WebOperationContext.Current.OutgoingRequest.Headers.Add("token", token);
                    var nodes = channel.GetNodes();
                }
            }
        }
コード例 #32
0
ファイル: Program.cs プロジェクト: masterorg/SvadaSystem
        static void Main(string[] args)
        {
            Thread.Sleep(2000);


            Uri address = new Uri("net.tcp://localhost:4000/IDatabaseManager");
            NetTcpBinding binding = new NetTcpBinding();

            ChannelFactory<IDatabaseManager> factory = new ChannelFactory<IDatabaseManager>(binding, new EndpointAddress(address));

            IDatabaseManager proxy = factory.CreateChannel();

            Console.WriteLine("Database Manager started");
            Digitalinput i = new Digitalinput();

            i.AutoOrManual = true;
            i.Descrition = "Pumpa";
            i.Driver = new SimulationDriver();
            i.TagName = "di1";

            Console.WriteLine("Adding DI tag");
            proxy.addDI(i);

            proxy.removeElement("bb");
            Console.WriteLine("Turn on scan");
            proxy.turnOnScan("di1");


            Console.ReadLine();
        }
コード例 #33
0
    public static void BasicHttpRequestReplyEchoString()
    {
        string testString = new string('a', 3000);
        var    host       = CreateWebHostBuilder(new string[0]).Build();

        using (host)
        {
            host.Start();
            var httpBinding = new System.ServiceModel.BasicHttpBinding();
            var factory     = new System.ServiceModel.ChannelFactory <ClientContract.IEchoService>(httpBinding,
                                                                                                   new System.ServiceModel.EndpointAddress(new Uri("http://localhost:8080/BasicWcfService/basichttp.svc")));
            var channel = factory.CreateChannel();
            var result  = channel.EchoString(testString);
            Assert.Equal(testString, result);
        }
    }
コード例 #34
0
    public static void ConcurrentNetTcpClientConnection()
    {
        string testString = new string('a', 3000);
        var    host       = CreateWebHostBuilder(new string[0]).Build();

        using (host)
        {
            host.Start();
            var binding = new System.ServiceModel.NetTcpBinding();
            var factory = new System.ServiceModel.ChannelFactory <ClientContract.ITestService>(binding,
                                                                                               new System.ServiceModel.EndpointAddress(new Uri("net.tcp://localhost:8808/nettcp.svc")));
            var channel = factory.CreateChannel();
            ((IChannel)channel).Open();
            var resultTask = channel.WaitForSecondRequestAsync();
            Thread.Sleep(TimeSpan.FromSeconds(1));
            channel.SecondRequest();
            var waitResult = resultTask.GetAwaiter().GetResult();
            Assert.True(waitResult, $"SecondRequest wasn't executed concurrently");
        }
    }
コード例 #35
0
    public static void MessageContract()
    {
        var host = CreateWebHostBuilder(new string[0]).Build();

        using (host)
        {
            host.Start();
            var binding = new System.ServiceModel.NetTcpBinding();
            var factory = new System.ServiceModel.ChannelFactory <ClientContract.ITestService>(binding,
                                                                                               new System.ServiceModel.EndpointAddress(new Uri("net.tcp://localhost:8808/nettcp.svc")));
            var channel = factory.CreateChannel();
            ((IChannel)channel).Open();

            var message = new ClientContract.TestMessage()
            {
                Header = "Header",
                Body   = new MemoryStream(Encoding.UTF8.GetBytes("Hello world"))
            };
            var result = channel.TestMessageContract(message);
            ((IChannel)channel).Close();
            Assert.Equal("Header from server", result.Header);
            Assert.Equal("Hello world from server", new StreamReader(result.Body, Encoding.UTF8).ReadToEnd());
        }
    }
コード例 #36
0
ファイル: ClientBase.cs プロジェクト: samcf111/unityMono5.5.0
 protected virtual TChannel CreateChannel()
 {
     return(ChannelFactory.CreateChannel());
 }