public void test_account_manager_as_service()
 {
     ChannelFactory<IAccountService> channelFactory = new ChannelFactory<IAccountService>("");
     IAccountService proxy = channelFactory.CreateChannel();
     (proxy as ICommunicationObject).Open();
     channelFactory.Close();
 }
        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;
            }
        }
Esempio n. 3
0
		public ImitatorServiceFactory()
		{
			var binding = BindingHelper.CreateBindingFromAddress("net.pipe://127.0.0.1/GKImitator/");
			var endpointAddress = new EndpointAddress(new Uri("net.pipe://127.0.0.1/GKImitator/"));
			_channelFactory = new ChannelFactory<IImitatorService>(binding, endpointAddress);
			_channelFactory.Open();
		}
Esempio n. 4
0
        public WCFClient(IEventAggregator eventBus) {
            _eventBus = eventBus;
            _pipeFactory = new ChannelFactory<IUpdaterWCF>(new NetNamedPipeBinding(), new EndpointAddress(
                "net.pipe://localhost/UpdaterWCF_Pipe"));

            _pipeProxy = _pipeFactory.CreateChannel();
        }
Esempio n. 5
0
        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();
        }
Esempio n. 6
0
		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;
		}
Esempio n. 7
0
 public Client(String URL)
 {
     BasicHttpBinding myBinding = new BasicHttpBinding();
     EndpointAddress  myEndpoint = new EndpointAddress(URL);
     myChannelFactory = new ChannelFactory<Server.IServerService>(myBinding, myEndpoint);
     comInterface = myChannelFactory.CreateChannel();
 }
Esempio n. 8
0
        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();
        }
        void MainPageLoaded(object sender, RoutedEventArgs e)
        {
            // Simple Version
            var basicHttpBinding = new BasicHttpBinding();
            var endpointAddress = new EndpointAddress("http://localhost:50738/UserGroupEvent.svc");
            var userGroupEventService = new ChannelFactory<IAsyncUserGroupEventService>(basicHttpBinding, endpointAddress).CreateChannel();

            AsyncCallback asyncCallBack = delegate(IAsyncResult result)
            {
                var response = ((IAsyncUserGroupEventService)result.AsyncState).EndGetUserGroupEvent(result);
                Dispatcher.BeginInvoke(() => SetUserGroupEventData(response));
            };
            userGroupEventService.BeginGetUserGroupEvent("123", asyncCallBack, userGroupEventService);

            // Deluxe Variante mit eigenem Proxy
            var channel = new UserGroupEventServiceProxy("BasicHttpBinding_IAsyncUserGroupEventService").Channel;
            channel.BeginGetUserGroupEvent("123", ProcessResult, channel);

            // Variante mit Faulthandler
            using (var scope = new OperationContextScope((IContextChannel)channel))
            {
                var messageHeadersElement = OperationContext.Current.OutgoingMessageHeaders;
                messageHeadersElement.Add(MessageHeader.CreateHeader("DoesNotHandleFault", "", true));
                channel.BeginGetUserGroupEventWithFault("123", ProcessResultWithFault, channel);
            }
        }
Esempio n. 10
0
        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());
            }
        }
Esempio n. 11
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;
        }
        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);
        }
Esempio n. 13
0
        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();
        }
Esempio n. 14
0
        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();
        }
Esempio n. 15
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();
                }
            }
        }
Esempio n. 16
0
 public static ITestRunner RegisterAsServer(ITestOutput output, Options options)
 {
     var host = new ServiceHost(output);
     int i;
     for (i = 0; i < 50; i += 10) {
         try {
             host.AddServiceEndpoint(typeof(ITestOutput), BindingFactory(), "http://localhost:" + (StartPort + i) + "/");
             break;
         } catch (AddressAlreadyInUseException) {
         }
     }
     host.Open();
     var start = DateTime.Now;
     Exception final = null;
     var res = new ChannelFactory<ITestRunner>(BindingFactory(), "http://localhost:" + (StartPort + i + 1) + "/").CreateChannel();
     while (DateTime.Now - start < TimeSpan.FromSeconds(5)) {
         try {
             res.Ping();
             return res;
         } catch (Exception e) {
             final = e;
         }
     }
     throw final;
 }
Esempio n. 17
0
        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);
        }
        public FileTransferServiceProxy()
        {
            this.m_BasicHttpBinding = new BasicHttpBinding();
            this.m_EndpointAddress = new EndpointAddress(EndpointAddressUrl);

            this.m_BasicHttpBinding.Security.Mode = BasicHttpSecurityMode.TransportWithMessageCredential;
            this.m_BasicHttpBinding.Security.Message.ClientCredentialType = BasicHttpMessageCredentialType.UserName;
            this.m_BasicHttpBinding.MaxReceivedMessageSize = 2147483647;

            XmlDictionaryReaderQuotas readerQuotas = new XmlDictionaryReaderQuotas();
            readerQuotas.MaxArrayLength = 25 * 208000;
            readerQuotas.MaxStringContentLength = 25 * 208000;
            this.m_BasicHttpBinding.ReaderQuotas = readerQuotas;

            this.m_ChannelFactory = new ChannelFactory<Contract.IFileTransferService>(this.m_BasicHttpBinding, this.m_EndpointAddress);
            this.m_ChannelFactory.Credentials.UserName.UserName = YellowstonePathology.YpiConnect.Contract.Identity.GuestWebServiceAccount.UserName;
            this.m_ChannelFactory.Credentials.UserName.Password = YellowstonePathology.YpiConnect.Contract.Identity.GuestWebServiceAccount.Password;

            foreach (System.ServiceModel.Description.OperationDescription op in this.m_ChannelFactory.Endpoint.Contract.Operations)
            {
                var dataContractBehavior = op.Behaviors.Find<System.ServiceModel.Description.DataContractSerializerOperationBehavior>();
                if (dataContractBehavior != null)
                {
                    dataContractBehavior.MaxItemsInObjectGraph = int.MaxValue;
                }
            }

            this.m_FileTransferServiceChannel = this.m_ChannelFactory.CreateChannel();
        }
        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);
            }
        }
Esempio n. 20
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));
                }

            }
        }
Esempio n. 21
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");
            }
        }
Esempio n. 22
0
        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();
        }
Esempio n. 23
0
 private static void Abort(IChannel channel, ChannelFactory channelFactory)
 {
     if (channel != null)
         channel.Abort();
     if (channelFactory != null)
         channelFactory.Abort();
 }
Esempio n. 24
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();
        }
Esempio n. 25
0
        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();
        }
        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();
        }
Esempio n. 27
0
        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);
        }
        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();
            }
        }
Esempio n. 29
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();
 }
Esempio n. 30
0
        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());
            }
        }
Esempio n. 31
0
        public static void ChangeWcfTimeout(DomainContext context, TimeSpan sendTimeout, TimeSpan receiveTimeout)
        {
            PropertyInfo property = context.GetType().GetProperty("ChannelFactory");

            if (property == null)
            {
                throw new InvalidOperationException("There is no 'ChannelFactory' property on the DomainClient.");
            }
            System.ServiceModel.ChannelFactory factory = (System.ServiceModel.ChannelFactory)property.GetValue(context, null);
            factory.Endpoint.Binding.ReceiveTimeout = receiveTimeout;
            factory.Endpoint.Binding.SendTimeout    = sendTimeout;
        }
 public static void ChangeWcfTimeout(DomainContext context, TimeSpan sendTimeout, TimeSpan receiveTimeout)
 {
     try
     {
         PropertyInfo property = context.GetType().GetProperty("ChannelFactory");
         if (property != null)
         {
             System.ServiceModel.ChannelFactory factory = (System.ServiceModel.ChannelFactory)property.GetValue(context, null);
             factory.Endpoint.Binding.ReceiveTimeout = receiveTimeout;
             factory.Endpoint.Binding.SendTimeout    = sendTimeout;
         }
     }
     catch (Exception e)
     {
     }
 }
Esempio n. 33
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();
            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);
        }
    }
Esempio n. 34
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());
        }
    }
Esempio n. 35
0
 public ChannelFactoryRef(ChannelFactory <TChannel> channelFactory)
 {
     this.channelFactory = channelFactory;
 }
Esempio n. 36
0
 public ClientRuntimeChannel(ServiceEndpoint endpoint,
                             ChannelFactory channelFactory, EndpointAddress remoteAddress, Uri via)
     : this(endpoint.CreateRuntime(), endpoint.Contract, channelFactory.DefaultOpenTimeout, channelFactory.DefaultCloseTimeout, null, channelFactory.OpenedChannelFactory, endpoint.Binding.MessageVersion, remoteAddress, via)
 {
 }
Esempio n. 37
0
 internal ClientBase(ChannelFactory <TChannel> factory)
     : this(null, factory)
 {
 }
Esempio n. 38
0
 internal ClientBase(InstanceContext instance, ChannelFactory <TChannel> factory)
 {
     // FIXME: use instance
     ChannelFactory = factory;
 }
Esempio n. 39
0
 internal virtual void Initialize(InstanceContext instance,
                                  string endpointConfigurationName, EndpointAddress remoteAddress)
 {
     // FIXME: use instance
     ChannelFactory = new ChannelFactory <TChannel> (endpointConfigurationName, remoteAddress);
 }
Esempio n. 40
0
 internal virtual void Initialize(InstanceContext instance,
                                  Binding binding, EndpointAddress remoteAddress)
 {
     // FIXME: use instance
     ChannelFactory = new ChannelFactory <TChannel> (binding, remoteAddress);
 }
Esempio n. 41
0
 protected virtual TChannel CreateChannel()
 {
     return(ChannelFactory.CreateChannel());
 }
Esempio n. 42
0
 internal ChannelBase(ServiceEndpoint endpoint, ChannelFactory factory)
 {
     this.endpoint = endpoint;
     this.factory  = factory;
 }
Esempio n. 43
0
 protected override TChannel CreateChannel()
 {
     return(ChannelFactory.CreateChannel());
 }
Esempio n. 44
0
 public ChannelFactoryRef(ChannelFactory <TChannel> channelFactory)
 {
     _channelFactory = channelFactory;
 }
Esempio n. 45
0
 internal ClientBase(ChannelFactory <TChannel> factory)
 {
     ChannelFactory = factory;
 }
Esempio n. 46
0
 public DummyClientBase(ChannelFactory <T> factory)
     : base(factory)
 {
 }