Esempio n. 1
0
        private static void AcceptChannelTest()
        {
            var binding = new NetTcpBinding();
            var listener = binding.Start(address);
            var connections = from channel in listener.GetChannels()
                           select new
                           {
                               Messages = channel.GetMessages(),
                               Response = channel.GetConsumer()
                           };

            connections.Subscribe(item =>
            {
                item.Response.Publish(Message.CreateMessage(binding.MessageVersion, "Test", "Echo:" + "Connected"));

                /*
                      (from message in channel.Messages
                       let input = message.GetBody<string>()
                       from response in new[] { Message.CreateMessage(version, "", "Echo:" + input) }
                       select response)
                      .Subscribe(channel.Response);

                 */
                item.Messages.Subscribe((message) =>
                {
                    var input = message.GetBody<string>();
                    var output = Message.CreateMessage(binding.MessageVersion, "", "Echo:" + input);
                    item.Response.Publish(output);
                });
            });
        }
        public ViewResult Book(BookingModel model)
        {
            var request = new BookRequest
            {
                RoomNumber = model.RoomNumber,
                PersonName = model.PersonName,
                BeginAt = model.BeginAt,
                EndAt = model.EndAt
            };

            var binding = new NetTcpBinding();
            var endpointAddress = new EndpointAddress("net.tcp://*****:*****@ViewBag.Title = "Booking completed";
                return View("Success", model);
            }

            @ViewBag.Title = "Booking failed";
            @ViewBag.Message = result.Message;

            return View("Failed");
        }
 /// <summary>
 /// Start the server
 /// </summary>
 /// <param name="address">the address that the server binds to</param>
 static void StartServer(string address)
 {
     ServiceHost host = null;
     try
     {
         NetTcpBinding tcpBinding = new NetTcpBinding();
         //set the maximum message size
         tcpBinding.MaxReceivedMessageSize = System.Int32.MaxValue;
         tcpBinding.ReaderQuotas.MaxArrayLength = System.Int32.MaxValue;
         //start the service
         host = new ServiceHost(typeof(ATCMasterControllerImpl));
         host.AddServiceEndpoint(typeof(IATCMasterController), tcpBinding, "net.tcp://" + address);
         host.Open();
         System.Console.WriteLine("Press Enter to exit");
         //keep server running until enter is pressed
         System.Console.ReadLine();
         //exit
         host.Close();
     }
     catch (Exception e)
     {
         System.Console.WriteLine(e.Message);
         if (host != null)
             host.Close();
         StartServer(address);
     }
 }
Esempio n. 4
0
		public OrationiSlave()
		{
			Binding binding = new NetTcpBinding(SecurityMode.None);
			EndpointAddress defaultEndpointAddress = new EndpointAddress("net.tcp://localhost:57344/Orationi/Master/v1/");
			EndpointAddress discoveredEndpointAddress = DiscoverMaster();
			ContractDescription contractDescription = ContractDescription.GetContract(typeof(IOrationiMasterService));
			ServiceEndpoint serviceEndpoint = new ServiceEndpoint(contractDescription, binding, discoveredEndpointAddress ?? defaultEndpointAddress);
			var channelFactory = new DuplexChannelFactory<IOrationiMasterService>(this, serviceEndpoint);

			try
			{
				channelFactory.Open();
			}
			catch (Exception ex)
			{
				channelFactory?.Abort();
			}

			try
			{
				_masterService = channelFactory.CreateChannel();
				_communicationObject = (ICommunicationObject)_masterService;
				_communicationObject.Open();
			}
			catch (Exception ex)
			{
				if (_communicationObject != null && _communicationObject.State == CommunicationState.Faulted)
					_communicationObject.Abort();
			}
		}
 public OrionInfoServiceWindows(string username, string password, bool v3 = false)
 {
     _endpoint = v3 ? Settings.Default.OrionV3EndpointPathAD : Settings.Default.OrionEndpointPathAD;
     _endpointConfigName = "OrionWindowsTcpBinding";
     _binding = new NetTcpBinding("Windows");
     _credentials = new WindowsCredential(username, password);
 }
Esempio n. 6
0
        public bool Connect(ClientCrawlerInfo clientCrawlerInfo)
        {
            try
            {
                var site = new InstanceContext(this);

                var binding = new NetTcpBinding(SecurityMode.None);
                //var address = new EndpointAddress("net.tcp://localhost:22222/chatservice/");

                var address = new EndpointAddress("net.tcp://193.124.113.235:22222/chatservice/");
                var factory = new DuplexChannelFactory<IRemoteCrawler>(site, binding, address);

                proxy = factory.CreateChannel();
                ((IContextChannel)proxy).OperationTimeout = new TimeSpan(1, 0, 10);

                clientCrawlerInfo.ClientIdentifier = _singletoneId;
                proxy.Join(clientCrawlerInfo);

                return true;
            }

            catch (Exception ex)
            {
                MessageBox.Show("Error happened" + ex.Message);
                return false;
            }
        }
 public NCMWindowsAuthInfoService(string username, string password)
 {
     _endpoint = Settings.Default.NCMWindowsEndpointPath;
     _endpointConfigName = "NCMWindowsTcpBinding_InformationServicev2";
     _binding = new NetTcpBinding("Windows");
     _credentials = new WindowsCredential(username, password);
 }
Esempio n. 8
0
		static void Main()
		{
			// только не null, ибо возникнет исключение
			//var baseAddress = new Uri("http://localhost:8002/MyService");
			var host = new ServiceHost(typeof(MyContractClient));//, baseAddress);

			host.Open();

			//var otherBaseAddress = new Uri("http://localhost:8001/");
			var otherHost = new ServiceHost(typeof(MyOtherContractClient));//, otherBaseAddress);
			var wsBinding = new BasicHttpBinding();
			var tcpBinding = new NetTcpBinding();
			otherHost.AddServiceEndpoint(typeof(IMyOtherContract), wsBinding, "http://localhost:8001/MyOtherService");
			otherHost.AddServiceEndpoint(typeof(IMyOtherContract), tcpBinding, "net.tcp://localhost:8003/MyOtherService");

			//AddHttpGetMetadata(otherHost);
			AddMexEndpointMetadata(otherHost);

			otherHost.Open();


			// you can access http://localhost:8002/MyService
			Application.EnableVisualStyles();
			Application.SetCompatibleTextRenderingDefault(false);
			Application.Run(new Host());

			otherHost.Close();

			host.Close();

			// you can not access http://localhost:8002/MyService
		}
        /// <summary>
        /// 截获从Client端发送的消息转发到目标终结点并获得返回值给Client端
        /// </summary>
        /// <param name="requestMessage"></param>
        /// <returns></returns>
        public Message ProcessMessage(Message requestMessage)
        {
            //Binding binding = null;
            EndpointAddress endpointAddress = null;
            GetServiceEndpoint(requestMessage, out endpointAddress);
            IDuplexRouterCallback callback = OperationContext.Current.GetCallbackChannel<IDuplexRouterCallback>();
            NetTcpBinding tbinding = new NetTcpBinding("netTcpExpenseService_ForSupplier");
            using (DuplexChannelFactory<IRouterService> factory = new DuplexChannelFactory<IRouterService>(new InstanceContext(null, new DuplexRouterCallback(callback)), tbinding, endpointAddress))
            {

                factory.Endpoint.Behaviors.Add(new MustUnderstandBehavior(false));
                IRouterService proxy = factory.CreateChannel();

                using (proxy as IDisposable)
                {
                    // 请求消息记录
                    IClientChannel clientChannel = proxy as IClientChannel;
                    //Console.WriteLine(String.Format("Request received at {0}, to {1}\r\n\tAction: {2}", DateTime.Now, clientChannel.RemoteAddress.Uri.AbsoluteUri, requestMessage.Headers.Action));
                    if (WcfServerManage.IsDebug)
                        hostwcfMsg(DateTime.Now, String.Format("路由请求消息发送:  {0}", clientChannel.RemoteAddress.Uri.AbsoluteUri));
                    // 调用绑定的终结点的服务方法
                    Message responseMessage = proxy.ProcessMessage(requestMessage);

                    // 应答消息记录
                    //Console.WriteLine(String.Format("Reply received at {0}\r\n\tAction: {1}", DateTime.Now, responseMessage.Headers.Action));
                    //Console.WriteLine();
                    //hostwcfMsg(DateTime.Now, String.Format("应答消息: {0}", responseMessage.Headers.Action));
                    return responseMessage;
                }
            }
        }
Esempio n. 10
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. 11
0
        public ServiceAgent(string Url)
        {
            try
            {
                 InstanceContext context = new InstanceContext(this);
                 NetTcpBinding binding = new NetTcpBinding(SecurityMode.None);
                 binding.MaxReceivedMessageSize = 2147483647;
                 binding.ReaderQuotas.MaxDepth= 2147483647;
                 binding.ReaderQuotas.MaxStringContentLength=2147483647;
                 binding.ReaderQuotas.MaxArrayLength= 2147483647;
                 binding.ReaderQuotas.MaxBytesPerRead= 2147483647;
                 binding.ReaderQuotas.MaxNameTableCharCount = 2147483647;
                 binding.OpenTimeout = TimeSpan.FromMinutes(10);
                 binding.SendTimeout = TimeSpan.FromMinutes(20);
                 binding.ReceiveTimeout = TimeSpan.FromMinutes(20);
                 binding.MaxBufferPoolSize = 2147483647;

                _proxy = new KryptonServiceProxy(context, binding, Url);
                _proxy.Open();
            }
               catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                _proxy = null;
            }
        }
Esempio n. 12
0
        public byte[] GetFile(ClassLibrary.Entites.File file, long partNumber)
        {
            PNRPManager manager = PeerServiceHost.PNRPManager;
            List<ClassLibrary.Entites.Peer> foundPeers = manager.ResolveByPeerName(file.PeerName);

            if (foundPeers.Count != 0) 
            {
                ClassLibrary.Entites.Peer peer = foundPeers.FirstOrDefault();

                EndpointAddress endpointAddress = new EndpointAddress(string.Format("net.tcp://{0}:{1}/PeerToPeerClient.Services/PeerService",
                    peer.PeerHostName, ClassLibrary.Config.LocalPort));

                NetTcpBinding tcpBinding = new NetTcpBinding(SecurityMode.None);
                PeerServiceClient client = new PeerServiceClient(tcpBinding, endpointAddress);

                byte[] data = null;

                try
                {
                    data = client.TransferFile(file, partNumber);
                }
                catch
                {
                    throw new Exception("Unreachable host '" + file.PeerName);
                }

                return data;
            }

            else
            {
                throw new Exception("Unable to resolve peer " +  file.PeerName);
            }
        }
Esempio n. 13
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 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);
        }
    }
Esempio n. 15
0
        public Form1()
        {
            InitializeComponent();
            IntPtr dummyHandle = Handle;

            lvMission.DoubleBuffer(true);
            lvNDock.DoubleBuffer(true);
            lvMission.LoadColumnWithOrder(Properties.Settings.Default.MissionColumnWidth);
            lvNDock.LoadColumnWithOrder(Properties.Settings.Default.DockColumnWidth);

            var host = new RemoteHost(this);
            servHost = new ServiceHost(host);
            if (Properties.Settings.Default.NetTcp)
            {
                var bind = new NetTcpBinding(SecurityMode.None);
                bind.Security.Message.ClientCredentialType = MessageCredentialType.UserName;
                servHost.AddServiceEndpoint(typeof(KCB.RPC.IUpdateNotification), bind, new Uri("net.tcp://localhost/kcb-update-channel"));
                servHost.Credentials.UserNameAuthentication.CustomUserNamePasswordValidator = new HogeFugaValidator();
                servHost.Credentials.UserNameAuthentication.UserNamePasswordValidationMode = System.ServiceModel.Security.UserNamePasswordValidationMode.Custom;
                Debug.WriteLine("Protocol:Net.Tcp");
                bTcpMode = true;
            }
            else
            {
                servHost.AddServiceEndpoint(typeof(KCB.RPC.IUpdateNotification), new NetNamedPipeBinding(), new Uri("net.pipe://localhost/kcb-update-channel"));
                Debug.WriteLine("Protocol:Net.Pipe");
            }
            servHost.Open();

            //起動し終えたのでシグナル状態へ
            Program._mutex.ReleaseMutex();

        }
Esempio n. 16
0
        static void Main(string[] args)
        {

            NetTcpBinding binding = new NetTcpBinding(SecurityMode.Transport);
            string address = "net.tcp://localhost:9999/WCFService";
            binding.Security.Transport.ClientCredentialType = TcpClientCredentialType.Certificate;

            ServiceHost host = new ServiceHost(typeof(Service));
            host.Credentials.ClientCertificate.Authentication.CertificateValidationMode = X509CertificateValidationMode.ChainTrust;
            host.Credentials.ClientCertificate.Authentication.RevocationMode = X509RevocationMode.NoCheck;
            host.AddServiceEndpoint(typeof(IContract), binding, address);
            host.Credentials.ServiceCertificate.SetCertificate("CN=srv", StoreLocation.LocalMachine, StoreName.My);
            host.Open();

            NetTcpBinding bindingForCustomValidation = new NetTcpBinding(SecurityMode.Transport);
            string addressForCustomValidation = "net.tcp://localhost:10000/WCFService";
            bindingForCustomValidation.Security.Transport.ClientCredentialType = TcpClientCredentialType.Certificate;

            ServiceHost hostForCustomValidation = new ServiceHost(typeof(Service));
            hostForCustomValidation.Credentials.ClientCertificate.Authentication.CertificateValidationMode = X509CertificateValidationMode.Custom;
            hostForCustomValidation.Credentials.ClientCertificate.Authentication.CustomCertificateValidator = new CustomValidator();
            hostForCustomValidation.Credentials.ClientCertificate.Authentication.RevocationMode = X509RevocationMode.NoCheck;
            hostForCustomValidation.AddServiceEndpoint(typeof(IContract), bindingForCustomValidation, addressForCustomValidation);
            hostForCustomValidation.Credentials.ServiceCertificate.SetCertificate("CN=srv", StoreLocation.LocalMachine, StoreName.My);
            hostForCustomValidation.Open();

            Console.WriteLine("WCFService is opened. Press <enter> to finish...");
            Console.ReadLine();

            host.Close();
        }
Esempio n. 17
0
 /// <summary>
 /// Initialize binding defaults
 /// </summary>
 static ReplyDispatcher()
 {
     using (ISchedulerHelper helper = SchedulerHelperFactory.GetInstance())
     {
         binding = helper.GetVertexServiceBinding();
     }
 }
Esempio n. 18
0
    public static void DuplexClientBaseOfT_OverNetTcp_Synchronous_Call()
    {
        DuplexClientBase<IWcfDuplexService> duplexService = null;
        Guid guid = Guid.NewGuid();

        try
        {
            NetTcpBinding binding = new NetTcpBinding();
            binding.Security.Mode = SecurityMode.None;

            WcfDuplexServiceCallback callbackService = new WcfDuplexServiceCallback();
            InstanceContext context = new InstanceContext(callbackService);

            duplexService = new MyDuplexClientBase<IWcfDuplexService>(context, binding, new EndpointAddress(Endpoints.Tcp_NoSecurity_Callback_Address));
            IWcfDuplexService proxy = duplexService.ChannelFactory.CreateChannel();

            // Ping on another thread.
            Task.Run(() => proxy.Ping(guid));
            Guid returnedGuid = callbackService.CallbackGuid;

            Assert.True(guid == returnedGuid, 
                string.Format("The sent GUID does not match the returned GUID. Sent '{0}', Received: '{1}'", guid, returnedGuid)); 

            ((ICommunicationObject)duplexService).Close();
        }
        finally
        {
            if (duplexService != null && duplexService.State != CommunicationState.Closed)
            {
                duplexService.Abort();
            }
        }
    }
        private void button1_Click(object sender, EventArgs e)
        {
            string page = textBox1.Text;

            try
            {
                EndpointAddress address = new EndpointAddress(new Uri("net.tcp://localhost:2137/Server"));
                NetTcpBinding binding = new NetTcpBinding();
                binding.MaxBufferPoolSize = 4 * 128 * 1024 * 1024;
                binding.MaxBufferSize = 128 * 1024 * 1024;
                binding.MaxReceivedMessageSize = 128 * 1024 * 1024;
                ChannelFactory<IPictureService> fac = new ChannelFactory<IPictureService>(binding, address);
                fac.Open();
                var svc = fac.CreateChannel();

                MessageBox.Show(svc.TextMe("World"));
                Picture pic = svc.DownloadPicture(page);
                Bitmap bmp = pic.GetBitmap();
                pictureBox1.Image = new Bitmap(bmp, new Size(bmp.Width < 894 ? bmp.Width : 894, bmp.Height < 542 ? bmp.Height : 542));
            }
            catch (EndpointNotFoundException ex)
            {
                MessageBox.Show("Brak połączenia z serwerem.\n\n" + ex.Message.ToString());
            }
            
            

        }
    public static void ServiceContract_TypedProxy_AsyncTask_CallbackReturn()
    {
        DuplexChannelFactory<IWcfDuplexTaskReturnService> factory = null;
        Guid guid = Guid.NewGuid();

        NetTcpBinding binding = new NetTcpBinding();
        binding.Security.Mode = SecurityMode.None;

        DuplexTaskReturnServiceCallback callbackService = new DuplexTaskReturnServiceCallback();
        InstanceContext context = new InstanceContext(callbackService);

        try
        {
            factory = new DuplexChannelFactory<IWcfDuplexTaskReturnService>(context, binding, new EndpointAddress(Endpoints.Tcp_NoSecurity_TaskReturn_Address));
            IWcfDuplexTaskReturnService serviceProxy = factory.CreateChannel();

            Task<Guid> task = serviceProxy.Ping(guid);

            Guid returnedGuid = task.Result;

            Assert.Equal(guid, returnedGuid);

            factory.Close();
        }
        finally
        {
            if (factory != null && factory.State != CommunicationState.Closed)
            {
                factory.Abort();
            }
        }
    }
Esempio n. 21
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);
            }
        }
    }
Esempio n. 22
0
        public Window()
        {
            InitializeComponent();
            _um6Driver = new Um6Driver("COM1", 115200);
            _um6Driver.Init();
            _servoDriver = new ServoDriver();
            _updateTimer = new System.Timers.Timer(50);
            _updateTimer.Elapsed += _updateTimer_Elapsed;
            _cameraDriver = new CameraDriver(this.Handle.ToInt64());
            _cameraDriver.Init(pictureBox.Handle.ToInt64());
            _cameraDriver.CameraCapture += _cameraDriver_CameraCapture;

            // initialize the service
            //_host = new ServiceHost(typeof(SatService));
            NetTcpBinding binding = new NetTcpBinding();
            binding.MaxReceivedMessageSize = 20000000;
            binding.MaxBufferPoolSize = 20000000;
            binding.MaxBufferSize = 20000000;
            binding.Security.Mode = SecurityMode.None;
            _service = new SatService(_cameraDriver);
            _host = new ServiceHost(_service);
            _host.AddServiceEndpoint(typeof(ISatService),
                                   binding,
                                   "net.tcp://localhost:8000");
            _host.Open();

            _stabPitchServo = 6000;
            _stabYawServo = 6000;
        }
Esempio n. 23
0
 protected override Binding GetBinding()
 {
     var binding = new NetTcpBinding(SecurityMode.None);
     binding.Security.Transport.ClientCredentialType = TcpClientCredentialType.None;
     binding.ReliableSession.Enabled = true;
     return binding;
 }
Esempio n. 24
0
    public static void NetTcpBinding_DuplexCallback_ReturnsXmlComplexType()
    {
        DuplexChannelFactory<IWcfDuplexService_Xml> factory = null;
        NetTcpBinding binding = null;
        WcfDuplexServiceCallback callbackService = null;
        InstanceContext context = null;
        IWcfDuplexService_Xml serviceProxy = null;
        Guid guid = Guid.NewGuid();

        try
        {
            binding = new NetTcpBinding();
            binding.Security.Mode = SecurityMode.None;

            callbackService = new WcfDuplexServiceCallback();
            context = new InstanceContext(callbackService);

            factory = new DuplexChannelFactory<IWcfDuplexService_Xml>(context, binding, new EndpointAddress(Endpoints.Tcp_NoSecurity_XmlDuplexCallback_Address));
            serviceProxy = factory.CreateChannel();

            serviceProxy.Ping_Xml(guid);
            XmlCompositeTypeDuplexCallbackOnly returnedType = callbackService.XmlCallbackGuid;

            // validate response
            Assert.True((guid.ToString() == returnedType.StringValue), String.Format("The Guid to string value sent was not the same as what was returned.\nSent: {0}\nReturned: {1}", guid.ToString(), returnedType.StringValue));

            ((ICommunicationObject)serviceProxy).Close();
            factory.Close();
        }
        finally
        {
            ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory);
        }
    }
Esempio n. 25
0
        public IDisposable StartServer()
        {
            var monitor = new ConnectionRateMonitor();
            var binding = new NetTcpBinding { Security = { Mode = SecurityMode.None } };
            var listener = binding.Start(this.ConnectArguments.CreateNetTcpAddress());
            Console.WriteLine("Listening on {0} for {1}", listener.Uri, typeof(SimpleObject).Name);

            listener.GetChannels()
                .SubscribeOn(System.Reactive.Concurrency.ThreadPoolScheduler.Instance)
                .Subscribe(c =>
                {
                    monitor.OnConnect();
                    c.GetMessages()
                        .Subscribe(
                            m =>
                            {
                                monitor.OnMessage();
                                var obj = m.GetBody<SimpleObject>();
                            },
                        ex => monitor.OnDisconnect(),
                        monitor.OnDisconnect);
                });

            monitor.Start();
            return Disposable.Create(listener.Abort);
        }
		public void DefaultValues ()
		{
			var n = new NetTcpBinding ();
			Assert.AreEqual (HostNameComparisonMode.StrongWildcard, n.HostNameComparisonMode, "#1");
			Assert.AreEqual (10, n.ListenBacklog, "#2");
			Assert.AreEqual (false, n.PortSharingEnabled, "#3");

			var tr = n.CreateBindingElements ().Find<TcpTransportBindingElement> ();
			Assert.IsNotNull (tr, "#tr1");
			Assert.AreEqual (false, tr.TeredoEnabled, "#tr2");
			Assert.AreEqual ("net.tcp", tr.Scheme, "#tr3");

			Assert.IsFalse (n.TransactionFlow, "#4");
			var tx = n.CreateBindingElements ().Find<TransactionFlowBindingElement> ();
			Assert.IsNotNull (tx, "#tx1");

			Assert.AreEqual (SecurityMode.Transport, n.Security.Mode, "#sec1");
			Assert.AreEqual (ProtectionLevel.EncryptAndSign, n.Security.Transport.ProtectionLevel, "#sec2");
			Assert.AreEqual (TcpClientCredentialType.Windows/*huh*/, n.Security.Transport.ClientCredentialType, "#sec3");

			var bc = n.CreateBindingElements ();
			Assert.AreEqual (4, bc.Count, "#bc1");
			Assert.AreEqual (typeof (TransactionFlowBindingElement), bc [0].GetType (), "#bc2");
			Assert.AreEqual (typeof (BinaryMessageEncodingBindingElement), bc [1].GetType (), "#bc3");
			Assert.AreEqual (typeof (WindowsStreamSecurityBindingElement), bc [2].GetType (), "#bc4");
			Assert.AreEqual (typeof (TcpTransportBindingElement), bc [3].GetType (), "#bc5");
			
			Assert.IsFalse (n.CanBuildChannelFactory<IRequestChannel> (), "#cbf1");
			Assert.IsFalse (n.CanBuildChannelFactory<IOutputChannel> (), "#cbf2");
			Assert.IsFalse (n.CanBuildChannelFactory<IDuplexChannel> (), "#cbf3");
			Assert.IsTrue (n.CanBuildChannelFactory<IDuplexSessionChannel> (), "#cbf4");
		}
Esempio n. 27
0
        public void Start(string publishUrl, string subscribeUrl)
        {
            try
            {
                this.Inititalize();
                NetTcpBinding netTcpBinding = new NetTcpBinding(SecurityMode.None);
                netTcpBinding.ReceiveTimeout = TimeSpan.MaxValue;
                netTcpBinding.MaxBufferSize = 2000000;
                netTcpBinding.MaxReceivedMessageSize = 2000000L;
                this._publishServiceHost.AddServiceEndpoint(typeof(IMessageEvents), (Binding)netTcpBinding, publishUrl);
                this._publishServiceHost.Open();

                new WSDualHttpBinding(WSDualHttpSecurityMode.None).ReceiveTimeout = TimeSpan.MaxValue;

                Binding binding = (Binding)new NetTcpBinding(SecurityMode.None);
                binding.ReceiveTimeout = TimeSpan.MaxValue;
                new NetNamedPipeBinding(NetNamedPipeSecurityMode.None).ReceiveTimeout = TimeSpan.MaxValue;
                this._subscriptionManagerHost.AddServiceEndpoint(
                    typeof(IMessageSubscriptionService),
                    binding,
                    subscribeUrl);
                this._subscriptionManagerHost.Open();
            }
            catch (Exception ex)
            {
                EntLibLoggerExtensions.Log(this._logger, "Error trying to start the message broker service", ex);
            }
        }
Esempio n. 28
0
        public string GetSaludo()
        {
            Trace.TraceInformation("Accediendo al servicio interno...");

              Trace.TraceInformation("Intentando crear el proxy del servicio interno...");

              string pid = Process.GetCurrentProcess().Id.ToString();
              string ppid = Process.GetCurrentProcess().ProcessName;

              string wip =
            RoleEnvironment.Roles["HolaAzureWorker"].Instances[0]
              .InstanceEndpoints["InternalWorker"].IPEndpoint.ToString();

              Trace.TraceInformation(wip);

              var serviceAddress = new Uri(string.Format("net.tcp://{0}/{1}", wip, "helloservice"));
              var endpointAddress = new EndpointAddress(serviceAddress);
              var binding = new NetTcpBinding(SecurityMode.None);

              var service = ChannelFactory<IWorkerInternalService>.CreateChannel(binding, endpointAddress);

              //  var service = WebRole.factory.CreateChannel();

              string hora = service.GetInformacion();

              //  como hago para obtener una propiedad desde la clase web role
              Trace.TraceInformation("Funcionando...a punto de saludar...");
              return string.Format("Hola Mundo Azure!! {0}", hora);
        }
Esempio n. 29
0
        private void InitializeProxy(string IpAddress, CallBackFunctionSignature callback)
        {
            try
            {
                 Url = string.Format("net.tcp://{0}:8001/KryptonService", IpAddress);
                 _callback = callback;

                 InstanceContext context = new InstanceContext(this);
                 NetTcpBinding binding = new NetTcpBinding(SecurityMode.None);
                 binding.MaxReceivedMessageSize = 2147483647;
                 binding.ReaderQuotas.MaxDepth= 2147483647;
                 binding.ReaderQuotas.MaxStringContentLength=2147483647;
                 binding.ReaderQuotas.MaxArrayLength= 2147483647;
                 binding.ReaderQuotas.MaxBytesPerRead= 2147483647;
                 binding.ReaderQuotas.MaxNameTableCharCount = 2147483647;
                 binding.OpenTimeout = TimeSpan.FromMinutes(10);
                 binding.SendTimeout = TimeSpan.FromMinutes(20);
                 binding.ReceiveTimeout = TimeSpan.FromMinutes(20);
                 binding.MaxBufferPoolSize = 2147483647;

                _proxy = new KryptonServiceProxy(context, binding, Url);
                _proxy.Open();
            }
               catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                _proxy = null;
            }
        }
Esempio n. 30
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);
        }
Esempio n. 31
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());
            }
        }
        /// <summary>
        /// Connect to WCF service
        /// </summary>
        private void Connect()
        {
            var localSettings = ConnectionSettings.Load();
            //Create a NetTcp binding to the service and set some appropriate timeouts.
            //Use reliable connection so we know when we have been disconnected
            var plexServiceBinding = new NetTcpBinding();
            plexServiceBinding.OpenTimeout = TimeSpan.FromSeconds(2);
            plexServiceBinding.CloseTimeout = TimeSpan.FromSeconds(2);
            plexServiceBinding.SendTimeout = TimeSpan.FromSeconds(2);
            plexServiceBinding.ReliableSession.Enabled = true;
            plexServiceBinding.ReliableSession.InactivityTimeout = TimeSpan.FromMinutes(1);
            //Generate the endpoint from the local settings
            var plexServiceEndpoint = new EndpointAddress(localSettings.getServiceAddress());
            //Make a channel factory so we can create the link to the service
            var plexServiceChannelFactory = new ChannelFactory<PlexServiceCommon.Interface.ITrayInteraction>(plexServiceBinding, plexServiceEndpoint);

            _plexService = null;

            try
            {
                _plexService = plexServiceChannelFactory.CreateChannel();
                //If we lose connection to the service, set the object to null so we will know to reconnect the next time the tray icon is clicked
                ((ICommunicationObject)_plexService).Faulted += (s, e) => _plexService = null;
                ((ICommunicationObject)_plexService).Closed += (s, e) => _plexService = null;
            }
            catch
            {
                if (_plexService != null)
                {
                    _plexService = null;
                }
            }
        }
Esempio n. 33
0
 /// <summary>
 /// Open the service host.
 /// </summary>
 /// <param name="binding">A specific biding instance.</param>
 /// <param name="address">The endpoint address.</param>
 public void OpenServiceHost(System.ServiceModel.NetTcpBinding binding, string address)
 {
     if (base.CommunicationState == CommunicationState.Closed)
     {
         base.Initialise();
         base.ServiceHost.AddServiceEndpoint(typeof(Nequeo.Management.NetTcp.IServer), binding, address);
         OpenConnection();
     }
 }
Esempio n. 34
0
 /// <summary>
 /// Default constructor
 /// </summary>
 /// <param name="netTcpBinding">The netTcpBinding binding.</param>
 /// <param name="username">The UserName username</param>
 /// <param name="password">The UserName password</param>
 /// <param name="usernameWindows">The Windows ClientCredential username</param>
 /// <param name="passwordWindows">The Windows ClientCredential password</param>
 /// <param name="clientCertificate">The client x509 certificate.</param>
 /// <param name="validationMode">An enumeration that lists the ways of validating a certificate.</param>
 /// <param name="x509CertificateValidator">The certificate validator. If null then the certificate is always passed.</param>
 public Client(System.ServiceModel.NetTcpBinding netTcpBinding,
               string username                                   = null, string password = null,
               string usernameWindows                            = null, string passwordWindows = null,
               X509Certificate2 clientCertificate                = null,
               X509CertificateValidationMode validationMode      = X509CertificateValidationMode.Custom,
               X509CertificateValidator x509CertificateValidator = null) :
     base(
         new Uri(Nequeo.Management.NetTcp.Properties.Settings.Default.ServiceAddress),
         netTcpBinding,
         username, password, usernameWindows, passwordWindows, clientCertificate, validationMode, x509CertificateValidator)
 {
     OnCreated();
 }
Esempio n. 35
0
 /// <summary>
 /// Default constructor
 /// </summary>
 /// <param name="endPointAddress">The specific end point address</param>
 /// <param name="netTcpBinding">The netTcpBinding binding.</param>
 /// <param name="username">The UserName username</param>
 /// <param name="password">The UserName password</param>
 /// <param name="usernameWindows">The Windows ClientCredential username</param>
 /// <param name="passwordWindows">The Windows ClientCredential password</param>
 /// <param name="clientCertificate">The client x509 certificate.</param>
 /// <param name="validationMode">An enumeration that lists the ways of validating a certificate.</param>
 /// <param name="x509CertificateValidator">The certificate validator. If null then the certificate is always passed.</param>
 public Client(string endPointAddress, System.ServiceModel.NetTcpBinding netTcpBinding,
               string username                                   = null, string password = null,
               string usernameWindows                            = null, string passwordWindows = null,
               X509Certificate2 clientCertificate                = null,
               X509CertificateValidationMode validationMode      = X509CertificateValidationMode.Custom,
               X509CertificateValidator x509CertificateValidator = null) :
     base(
         new Uri(endPointAddress),
         netTcpBinding,
         username, password, usernameWindows, passwordWindows, clientCertificate, validationMode, x509CertificateValidator)
 {
     OnCreated();
 }
Esempio n. 36
0
        private static System.ServiceModel.Channels.Binding createBinding(MB.Util.Model.WcfCredentialInfo credentialInfo,
                                                                          bool isGZipCustomBinding, string usedbindingCfgName)
        {
            System.ServiceModel.Channels.Binding binding = null;
            var cfgInfo = credentialInfo;
            WcfServiceBindingType bindingType = getBindingType(credentialInfo);

            if (bindingType == WcfServiceBindingType.wsHttp)
            {
                string bindingCfgName;
                if (string.IsNullOrEmpty(usedbindingCfgName))
                {
                    bindingCfgName = System.Configuration.ConfigurationManager.AppSettings[HTTP_BINDING_NAME];
                }
                else
                {
                    bindingCfgName = usedbindingCfgName;
                }

                if (string.IsNullOrEmpty(bindingCfgName))
                {
                    throw new MB.Util.APPException(string.Format("wsHttp绑定需要配置{0}", HTTP_BINDING_NAME), MB.Util.APPMessageType.SysErrInfo);
                }

                //string gzip = System.Configuration.ConfigurationManager.AppSettings[ENABLE_GZIP_MESSAGE];

                if (!isGZipCustomBinding)
                {
                    binding = new WSHttpBinding(bindingCfgName);
                }
                else
                {
                    binding = new CustomBinding(bindingCfgName);
                }
            }
            else if (bindingType == WcfServiceBindingType.netTcp)
            {
                string cfgName = System.Configuration.ConfigurationManager.AppSettings[TCP_BINDING_NAME];
                if (string.IsNullOrEmpty(cfgName))
                {
                    throw new MB.Util.APPException(string.Format("netTcp 绑定需要配置{0}", TCP_BINDING_NAME), MB.Util.APPMessageType.SysErrInfo);
                }

                binding = new System.ServiceModel.NetTcpBinding(cfgName);
            }
            else
            {
                throw new MB.Util.APPException(string.Format("Wcf 客户端绑定目前不支持{0}", bindingType.ToString()), MB.Util.APPMessageType.SysErrInfo);
            }
            return(binding);
        }
Esempio n. 37
0
        /*
         * public static WebHttpBinding getWebHttpBinding(string bindingName)
         * {
         *  System.ServiceModel.WebHttpBinding binding = new System.ServiceModel.WebHttpBinding();
         *
         *  System.ServiceModel.ServiceBehaviorAttribute behavior = new System.ServiceModel.ServiceBehaviorAttribute();
         *
         *  behavior.MaxItemsInObjectGraph = 2147483647;
         *
         *  binding.Name = bindingName;
         *
         *  //binding.CloseTimeout = new TimeSpan(0, 1, 0);
         *  binding.CloseTimeout = new TimeSpan(0, 10, 0);
         *  //binding.OpenTimeout = new TimeSpan(0, 1, 0);
         *  binding.OpenTimeout = new TimeSpan(0, 10, 0);
         *  binding.ReceiveTimeout = new TimeSpan(0, 10, 0);
         *  //binding.SendTimeout = new TimeSpan(0, 1, 0);
         *  binding.SendTimeout = new TimeSpan(0, 10, 0);
         *  binding.AllowCookies = false;
         *  binding.BypassProxyOnLocal = false;
         *  binding.HostNameComparisonMode = System.ServiceModel.HostNameComparisonMode.StrongWildcard;
         *  binding.MaxBufferSize = 2147483647;
         *  binding.MaxBufferPoolSize = 2147483647;
         *  binding.MaxReceivedMessageSize = 2147483647;
         *  //binding.MessageEncoding = System.ServiceModel.WSMessageEncoding.Text;
         *  //binding.TextEncoding = System.Text.Encoding.UTF8;
         *  binding.TransferMode = System.ServiceModel.TransferMode.Streamed;
         *  binding.UseDefaultWebProxy = true;
         *
         *  binding.ReaderQuotas.MaxDepth = 2147483647;
         *  binding.ReaderQuotas.MaxStringContentLength = 2147483647;
         *  binding.ReaderQuotas.MaxArrayLength = 2147483647;
         *  binding.ReaderQuotas.MaxBytesPerRead = 2147483647;
         *  binding.ReaderQuotas.MaxNameTableCharCount = 2147483647;
         *
         *  //binding.Security.Mode = System.ServiceModel.BasicHttpSecurityMode.None;
         *  binding.Security.Transport.ClientCredentialType = System.ServiceModel.HttpClientCredentialType.None;
         *  binding.Security.Transport.ProxyCredentialType = System.ServiceModel.HttpProxyCredentialType.None;
         *  //binding.Security.Message.ClientCredentialType = System.ServiceModel.BasicHttpMessageCredentialType.UserName;
         *  //binding.Security.Message.AlgorithmSuite = System.ServiceModel.Security.SecurityAlgorithmSuite.Default;
         *
         *  return binding;
         * }
         */

        public static NetTcpBinding getNetTcpBinding(string bindingName)
        {
            System.ServiceModel.NetTcpBinding binding = new System.ServiceModel.NetTcpBinding();

            System.ServiceModel.ServiceBehaviorAttribute behavior = new System.ServiceModel.ServiceBehaviorAttribute();

            behavior.MaxItemsInObjectGraph = 2147483647;

            binding.Name = bindingName;

            /*
             * //binding.CloseTimeout = new TimeSpan(0, 1, 0);
             * binding.CloseTimeout = new TimeSpan(0, 10, 0);
             * //binding.OpenTimeout = new TimeSpan(0, 1, 0);
             * binding.OpenTimeout = new TimeSpan(0, 10, 0);
             * binding.ReceiveTimeout = new TimeSpan(0, 10, 0);
             * //binding.SendTimeout = new TimeSpan(0, 1, 0);
             * binding.SendTimeout = new TimeSpan(0, 10, 0);
             * binding.AllowCookies = false;
             * binding.BypassProxyOnLocal = false;
             * binding.HostNameComparisonMode = System.ServiceModel.HostNameComparisonMode.StrongWildcard;
             * binding.MaxBufferSize = 2147483647;
             * binding.MaxBufferPoolSize = 2147483647;
             * binding.MaxReceivedMessageSize = 2147483647;
             * binding.MessageEncoding = System.ServiceModel.WSMessageEncoding.Text;
             * binding.TextEncoding = System.Text.Encoding.UTF8;
             * binding.TransferMode = System.ServiceModel.TransferMode.Streamed;
             * binding.UseDefaultWebProxy = true;
             *
             * binding.ReaderQuotas.MaxDepth = 2147483647;
             * binding.ReaderQuotas.MaxStringContentLength = 2147483647;
             * binding.ReaderQuotas.MaxArrayLength = 2147483647;
             * binding.ReaderQuotas.MaxBytesPerRead = 2147483647;
             * binding.ReaderQuotas.MaxNameTableCharCount = 2147483647;
             *
             * binding.Security.Mode = System.ServiceModel.BasicHttpSecurityMode.None;
             * binding.Security.Transport.ClientCredentialType = System.ServiceModel.HttpClientCredentialType.None;
             * binding.Security.Transport.ProxyCredentialType = System.ServiceModel.HttpProxyCredentialType.None;
             * binding.Security.Message.ClientCredentialType = System.ServiceModel.BasicHttpMessageCredentialType.UserName;
             * binding.Security.Message.AlgorithmSuite = System.ServiceModel.Security.SecurityAlgorithmSuite.Default;
             */
            return(binding);
        }
Esempio n. 38
0
 public void TestTcpUrl()
 {
     using (var server = new System.ServiceModel.ServiceHost(new Service(), new Uri("net.tcp://127.0.0.1:6782")))
     {
         var binding = new System.ServiceModel.NetTcpBinding()
         {
             MaxConnections = 5
         };
         server.AddServiceEndpoint(typeof(IService), binding, "net.tcp://127.0.0.1:6782");
         server.Open();
         Thread.Sleep(100);
         using (var channelFactory = new System.ServiceModel.ChannelFactory <IService>(binding))
         {
             var client = channelFactory.CreateChannel(new EndpointAddress("net.tcp://127.0.0.1:6782"));
             var result = client.Execute(new byte[] { 1 });
             Assert.AreEqual(1, result[0]);
         }
     }
 }
Esempio n. 39
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");
        }
    }
        /// <summary>
        /// Соединяемся с сервисом
        /// </summary>
        /// <param name="serverIP"></param>
        /// <param name="serverPort"></param>
        /// <param name="person"></param>
        /// <param name="callback"></param>
        /// <returns></returns>
        public OperationResult <Person[]> Connect(string serverIP, string serverPort, Person person, ChatServiceCallback callback)
        {
            //Создается соединение с сервисом
            Binding         binding = new System.ServiceModel.NetTcpBinding();
            var             uri     = new Uri($"net.tcp://{serverIP}:{serverPort}");
            EndpointAddress address = new EndpointAddress(uri);

            _factory = new DuplexChannelFactory <IChatService>(callback, binding, address);

            _service = _factory.CreateChannel();

            if (_service == null)
            {
                throw new Exception("Не удалось создать соединение с сервисом");
            }

            OperationResult <Person[]> joinResult = _service.Join(person);

            return(joinResult);
        }
Esempio n. 41
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. 42
0
        internal static bool TryCreate(BindingElementCollection elements, out Binding binding)
        {
            binding = null;
            if (elements.Count > 6)
            {
                return(false);
            }

            // collect all binding elements
            TcpTransportBindingElement          transport = null;
            BinaryMessageEncodingBindingElement encoding  = null;
            TransactionFlowBindingElement       context   = null;
            ReliableSessionBindingElement       session   = null;
            SecurityBindingElement wsSecurity             = null;
            BindingElement         transportSecurity      = null;

            foreach (BindingElement element in elements)
            {
                if (element is SecurityBindingElement)
                {
                    wsSecurity = element as SecurityBindingElement;
                }
                else if (element is TransportBindingElement)
                {
                    transport = element as TcpTransportBindingElement;
                }
                else if (element is MessageEncodingBindingElement)
                {
                    encoding = element as BinaryMessageEncodingBindingElement;
                }
                else if (element is TransactionFlowBindingElement)
                {
                    context = element as TransactionFlowBindingElement;
                }
                else if (element is ReliableSessionBindingElement)
                {
                    session = element as ReliableSessionBindingElement;
                }
                else
                {
                    if (transportSecurity != null)
                    {
                        return(false);
                    }
                    transportSecurity = element;
                }
            }

            if (transport == null)
            {
                return(false);
            }
            if (encoding == null)
            {
                return(false);
            }
            if (context == null)
            {
                context = GetDefaultTransactionFlowBindingElement();
            }

            TcpTransportSecurity tcpTransportSecurity = new TcpTransportSecurity();
            UnifiedSecurityMode  mode = GetModeFromTransportSecurity(transportSecurity);

            NetTcpSecurity security;

            if (!TryCreateSecurity(wsSecurity, mode, session != null, transportSecurity, tcpTransportSecurity, out security))
            {
                return(false);
            }

            if (!SetTransportSecurity(transportSecurity, security.Mode, tcpTransportSecurity))
            {
                return(false);
            }

            NetTcpBinding netTcpBinding = new NetTcpBinding(transport, encoding, context, session, security);

            if (!netTcpBinding.IsBindingElementsMatch(transport, encoding, context, session))
            {
                return(false);
            }

            binding = netTcpBinding;
            return(true);
        }
Esempio n. 43
0
        /// <summary>
        /// Gets the remote ref.
        /// </summary>
        /// <param name="remoteEP">The remote endpoint.</param>
        /// <param name="epType">WCF interface that the remote object implements.
        /// Only needed for WCF RemotingMechanisms.
        /// It can be null when RemotingMechanisem TcpBinary is used.</param>
        /// <param name="remoteObjectPrefix">The remote object prefix.</param>
        /// <returns></returns>
        public static EndPointReference GetRemoteRef(EndPoint remoteEP, Type epType, string remoteObjectPrefix)
        {
            EndPointReference epr = null;

            switch (remoteEP.RemotingMechanism)
            {
            case RemotingMechanism.TcpBinary:
            {
                #region TcpBinary
                epr = new EndPointReference();
                string uri = "tcp://" + remoteEP.Host + ":" + remoteEP.Port + "/" + remoteObjectPrefix;
                epr.Instance = Activator.GetObject(typeof(GNode), uri);
                break;
                #endregion
            }

            case RemotingMechanism.WCFCustom:
            {
                #region WCFCustom
                System.ServiceModel.Channels.IChannelFactory <IExecutor> facExe = null;
                System.ServiceModel.Channels.IChannelFactory <IManager>  facMan = null;
                System.ServiceModel.Channels.IChannelFactory <IOwner>    facOwn = null;
                epr = new EndPointReference();
                switch (epType.Name)
                {
                case "IExecutor":
                {
                    facExe       = new ChannelFactory <IExecutor>(remoteEP.ServiceConfigurationName);
                    epr._fac     = facExe;
                    epr.Instance = facExe.CreateChannel(new EndpointAddress(remoteEP.FullAddress));
                    break;
                }

                case "IManager":
                {
                    facMan       = new ChannelFactory <IManager>(remoteEP.ServiceConfigurationName);
                    epr._fac     = facMan;
                    epr.Instance = facMan.CreateChannel(new EndpointAddress(remoteEP.FullAddress));
                    break;
                }

                case "IOwner":
                {
                    facOwn       = new ChannelFactory <IOwner>(remoteEP.ServiceConfigurationName);
                    epr._fac     = facOwn;
                    epr.Instance = facOwn.CreateChannel(new EndpointAddress(remoteEP.FullAddress));
                    break;
                }

                default:
                {
                    throw new Exception("This type of WCF Service contract type is not supported");
                }
                }

                break;
                #endregion
            }

            case RemotingMechanism.WCFTcp:
            {
                #region WCFTcp
                System.ServiceModel.Channels.IChannelFactory <IExecutor> facExe = null;
                System.ServiceModel.Channels.IChannelFactory <IManager>  facMan = null;
                System.ServiceModel.Channels.IChannelFactory <IOwner>    facOwn = null;
                remoteEP.Binding = WCFBinding.NetTcpBinding;
                epr = new EndPointReference();
                switch (epType.Name)
                {
                case "IExecutor":
                {
                    System.ServiceModel.NetTcpBinding tcpBin = (System.ServiceModel.NetTcpBinding)Utility.WCFUtils.GetWCFBinding(remoteEP);
                    facExe       = new ChannelFactory <IExecutor>(tcpBin);
                    epr._fac     = facExe;
                    epr.Instance = facExe.CreateChannel(new EndpointAddress(remoteEP.FullAddress));
                    break;
                }

                case "IManager":
                {
                    System.ServiceModel.NetTcpBinding tcpBin = (System.ServiceModel.NetTcpBinding)Utility.WCFUtils.GetWCFBinding(remoteEP);
                    facMan       = new ChannelFactory <IManager>(tcpBin);
                    epr._fac     = facMan;
                    epr.Instance = facMan.CreateChannel(new EndpointAddress(remoteEP.FullAddress));
                    break;
                }

                case "IOwner":
                {
                    System.ServiceModel.NetTcpBinding tcpBin = (System.ServiceModel.NetTcpBinding)Utility.WCFUtils.GetWCFBinding(remoteEP);
                    facOwn       = new ChannelFactory <IOwner>(tcpBin);
                    epr._fac     = facOwn;
                    epr.Instance = facOwn.CreateChannel(new EndpointAddress(remoteEP.FullAddress));
                    break;
                }

                default:
                {
                    throw new Exception("This type of WCF Service contract type is not supported");
                }
                }

                break;
                #endregion
            }

            case RemotingMechanism.WCFHttp:
            {
                #region WCFHttp
                System.ServiceModel.Channels.IChannelFactory <IExecutor> facExe = null;
                System.ServiceModel.Channels.IChannelFactory <IManager>  facMan = null;
                System.ServiceModel.Channels.IChannelFactory <IOwner>    facOwn = null;
                epr = new EndPointReference();
                remoteEP.Binding = WCFBinding.WSHttpBinding;
                switch (epType.Name)
                {
                case "IExecutor":
                {
                    System.ServiceModel.WSHttpBinding wsHttpBin = (System.ServiceModel.WSHttpBinding)Utility.WCFUtils.GetWCFBinding(remoteEP);
                    facExe       = new ChannelFactory <IExecutor>(wsHttpBin);
                    epr._fac     = facExe;
                    epr.Instance = facExe.CreateChannel(new EndpointAddress(remoteEP.FullAddress));
                    break;
                }

                case "IManager":
                {
                    System.ServiceModel.WSHttpBinding wsHttpBin = (System.ServiceModel.WSHttpBinding)Utility.WCFUtils.GetWCFBinding(remoteEP);
                    facMan       = new ChannelFactory <IManager>(wsHttpBin);
                    epr._fac     = facMan;
                    epr.Instance = facMan.CreateChannel(new EndpointAddress(remoteEP.FullAddress));
                    break;
                }

                case "IOwner":
                {
                    System.ServiceModel.WSHttpBinding wsHttpBin = (System.ServiceModel.WSHttpBinding)Utility.WCFUtils.GetWCFBinding(remoteEP);
                    facOwn       = new ChannelFactory <IOwner>(wsHttpBin);
                    epr._fac     = facOwn;
                    epr.Instance = facOwn.CreateChannel(new EndpointAddress(remoteEP.FullAddress));
                    break;
                }

                default:
                {
                    throw new Exception("This type of WCF Service contract type is not supported");
                }
                }

                break;
                #endregion
            }

            case RemotingMechanism.WCF:
            {
                #region WCF
                System.ServiceModel.Channels.IChannelFactory <IExecutor> facExe = null;
                System.ServiceModel.Channels.IChannelFactory <IManager>  facMan = null;
                System.ServiceModel.Channels.IChannelFactory <IOwner>    facOwn = null;
                epr = new EndPointReference();
                switch (epType.Name)
                {
                case "IExecutor":
                {
                    System.ServiceModel.Channels.Binding binding = Utility.WCFUtils.GetWCFBinding(remoteEP);
                    facExe       = new ChannelFactory <IExecutor>(binding);
                    epr._fac     = facExe;
                    epr.Instance = facExe.CreateChannel(new EndpointAddress(remoteEP.FullAddress));
                    break;
                }

                case "IManager":
                {
                    System.ServiceModel.Channels.Binding binding = Utility.WCFUtils.GetWCFBinding(remoteEP);
                    facMan       = new ChannelFactory <IManager>(binding);
                    epr._fac     = facMan;
                    epr.Instance = facMan.CreateChannel(new EndpointAddress(remoteEP.FullAddress));
                    break;
                }

                case "IOwner":
                {
                    System.ServiceModel.Channels.Binding binding = Utility.WCFUtils.GetWCFBinding(remoteEP);
                    facOwn       = new ChannelFactory <IOwner>(binding);
                    epr._fac     = facOwn;
                    epr.Instance = facOwn.CreateChannel(new EndpointAddress(remoteEP.FullAddress));
                    break;
                }

                default:
                {
                    throw new Exception("This type of WCF Service contract type is not supported");
                }
                }

                break;
                #endregion
            }

            default:
                return(null);
            }

            return(epr);
        }
Esempio n. 44
0
        /// <summary>
        /// Remotes this instance across a channel
        /// - if the own end point is valid:
        ///  - register a new channel, if not already done.
        ///  - if successful, then marshal this GNode object over the remoting channel
        /// </summary>
        private void RemoteSelf()
        {
            if (_OwnEP != null)
            {
                switch (_OwnEP.RemotingMechanism)
                {
                case (RemotingMechanism.TcpBinary):
                {
                    #region .NET Remoting Publish
                    if (!_ChannelRegistered)
                    {
                        try
                        {
                            _Channel = new TcpChannel(_OwnEP.Port);
                            //Hashtable properties = new Hashtable();

                            //// the name must be Empty in order to allow multiple TCP channels
                            //properties.Add("name", String.Empty);
                            //properties.Add("port", _OwnEP.Port);

                            //_Channel = new TcpChannel(
                            //    properties,
                            //    new BinaryClientFormatterSinkProvider(),
                            //    new BinaryServerFormatterSinkProvider());

                            ChannelServices.RegisterChannel(_Channel, false);
                            _ChannelRegistered = true;
                        }
                        catch (Exception e)
                        {
                            if (
                                object.ReferenceEquals(e.GetType(), typeof(System.Runtime.Remoting.RemotingException)) /* assuming: "The channel tcp is already registered." */
                                |
                                object.ReferenceEquals(e.GetType(), typeof(SocketException))                           /* assuming: "Only one usage of each socket address (protocol/network address/port) is normally permitted" */
                                )
                            {
                                _ChannelRegistered = true;
                            }
                            else
                            {
                                UnRemoteSelf();
                                throw new RemotingException("Could not register channel while trying to remote self: " + e.Message, e);
                            }
                        }
                    }

                    if (_ChannelRegistered)
                    {
                        try
                        {
                            logger.Info("Trying to publish a GNode at : " + _RemoteObjPrefix);
                            RemotingServices.Marshal(this, _RemoteObjPrefix);
                            logger.Info("GetObjectURI from remoting services : " + RemotingServices.GetObjectUri(this));
                            logger.Info("Server object type: " + RemotingServices.GetServerTypeForUri(RemotingServices.GetObjectUri(this)).FullName);
                        }
                        catch (Exception e)
                        {
                            UnRemoteSelf();
                            throw new RemotingException("Could not remote self.", e);
                        }
                    }
                    break;
                    #endregion
                }

                case RemotingMechanism.WCFCustom:
                {
                    #region Custom WCF Publish
                    try
                    {
                        _ServiceHost = new ServiceHost(this, new Uri(_OwnEP.FullAddress));
                        _ServiceHost.Open();
                    }
                    catch (Exception e)
                    {
                        UnRemoteSelf();
                        throw e;
                        //throw new Exception("Could not remote self.", e);
                    }

                    break;
                    #endregion
                }

                case RemotingMechanism.WCFTcp:
                {
                    #region Tcp WCF Publish
                    try
                    {
                        //create a new binding
                        _OwnEP.Binding = WCFBinding.NetTcpBinding;
                        System.ServiceModel.NetTcpBinding tcpBin = (System.ServiceModel.NetTcpBinding)Utility.WCFUtils.GetWCFBinding(_OwnEP);

                        Type contractType = null;

                        if (this is Alchemi.Core.IExecutor)
                        {
                            contractType = typeof(Alchemi.Core.IExecutor);
                        }
                        else if (this is Alchemi.Core.IManager)
                        {
                            contractType = typeof(Alchemi.Core.IManager);
                        }
                        else if (this is Alchemi.Core.IOwner)
                        {
                            contractType = typeof(Alchemi.Core.IOwner);
                        }

                        _ServiceHost = new ServiceHost(this, new Uri(_OwnEP.FullPublishingAddress));
                        Utility.WCFUtils.SetPublishingServiceHost(_ServiceHost);
                        _ServiceHost.AddServiceEndpoint(contractType, tcpBin, _OwnEP.FullPublishingAddress);

                        _ServiceHost.Open();
                    }
                    catch (Exception e)
                    {
                        UnRemoteSelf();
                        throw e;
                        //throw new Exception("Could not remote self.", e);
                    }

                    break;
                    #endregion
                }

                case RemotingMechanism.WCFHttp:
                {
                    #region Http WCF Publish
                    try
                    {
                        //create a new binding
                        _OwnEP.Binding = WCFBinding.WSHttpBinding;
                        System.ServiceModel.WSHttpBinding wsHttpBin = (System.ServiceModel.WSHttpBinding)Utility.WCFUtils.GetWCFBinding(_OwnEP);

                        Type contractType = null;

                        if (this is Alchemi.Core.IExecutor)
                        {
                            contractType = typeof(Alchemi.Core.IExecutor);
                        }
                        else if (this is Alchemi.Core.IManager)
                        {
                            contractType = typeof(Alchemi.Core.IManager);
                        }
                        else if (this is Alchemi.Core.IOwner)
                        {
                            contractType = typeof(Alchemi.Core.IOwner);
                        }

                        _ServiceHost = new ServiceHost(this, new Uri(_OwnEP.FullPublishingAddress));
                        Utility.WCFUtils.SetPublishingServiceHost(_ServiceHost);
                        _ServiceHost.AddServiceEndpoint(contractType, wsHttpBin, _OwnEP.FullPublishingAddress);

                        _ServiceHost.Open();
                    }
                    catch (Exception e)
                    {
                        UnRemoteSelf();
                        throw e;
                        //throw new Exception("Could not remote self.", e);
                    }

                    break;
                    #endregion
                }

                case RemotingMechanism.WCF:
                {
                    #region WCF Publish
                    try
                    {
                        //create a new binding
                        System.ServiceModel.Channels.Binding binding = Utility.WCFUtils.GetWCFBinding(_OwnEP);

                        Type contractType = null;

                        if (this is Alchemi.Core.IExecutor)
                        {
                            contractType = typeof(Alchemi.Core.IExecutor);
                        }
                        else if (this is Alchemi.Core.IManager)
                        {
                            contractType = typeof(Alchemi.Core.IManager);
                        }
                        else if (this is Alchemi.Core.IOwner)
                        {
                            contractType = typeof(Alchemi.Core.IOwner);
                        }

                        _ServiceHost = new ServiceHost(this, new Uri(_OwnEP.FullPublishingAddress));
                        Utility.WCFUtils.SetPublishingServiceHost(_ServiceHost);
                        _ServiceHost.AddServiceEndpoint(contractType, binding, _OwnEP.FullPublishingAddress);

                        _ServiceHost.Open();
                    }
                    catch (Exception e)
                    {
                        UnRemoteSelf();
                        throw e;
                        //throw new Exception("Could not remote self.", e);
                    }

                    break;
                    #endregion
                }
                }
            }
        }
        internal static bool TryCreate(BindingElementCollection elements, out Binding binding)
        {
            NetTcpSecurity security2;

            binding = null;
            if (elements.Count > 6)
            {
                return(false);
            }
            TcpTransportBindingElement          transport = null;
            BinaryMessageEncodingBindingElement encoding  = null;
            TransactionFlowBindingElement       context   = null;
            ReliableSessionBindingElement       session   = null;
            SecurityBindingElement sbe      = null;
            BindingElement         element6 = null;

            foreach (BindingElement element7 in elements)
            {
                if (element7 is SecurityBindingElement)
                {
                    sbe = element7 as SecurityBindingElement;
                }
                else if (element7 is TransportBindingElement)
                {
                    transport = element7 as TcpTransportBindingElement;
                }
                else if (element7 is MessageEncodingBindingElement)
                {
                    encoding = element7 as BinaryMessageEncodingBindingElement;
                }
                else if (element7 is TransactionFlowBindingElement)
                {
                    context = element7 as TransactionFlowBindingElement;
                }
                else if (element7 is ReliableSessionBindingElement)
                {
                    session = element7 as ReliableSessionBindingElement;
                }
                else
                {
                    if (element6 != null)
                    {
                        return(false);
                    }
                    element6 = element7;
                }
            }
            if (transport == null)
            {
                return(false);
            }
            if (encoding == null)
            {
                return(false);
            }
            if (context == null)
            {
                context = GetDefaultTransactionFlowBindingElement();
            }
            TcpTransportSecurity tcpTransportSecurity      = new TcpTransportSecurity();
            UnifiedSecurityMode  modeFromTransportSecurity = GetModeFromTransportSecurity(element6);

            if (!TryCreateSecurity(sbe, modeFromTransportSecurity, session != null, element6, tcpTransportSecurity, out security2))
            {
                return(false);
            }
            if (!SetTransportSecurity(element6, security2.Mode, tcpTransportSecurity))
            {
                return(false);
            }
            NetTcpBinding binding2 = new NetTcpBinding(transport, encoding, context, session, security2);

            if (!binding2.IsBindingElementsMatch(transport, encoding, context, session))
            {
                return(false);
            }
            binding = binding2;
            return(true);
        }