private void ConnectToMesh()
        {
            try
            {
                _instanceContext = new InstanceContext(this);

                _binding = new NetPeerTcpBinding("SharedTextEditorBinding");

                _channelFactory = new DuplexChannelFactory<ISharedTextEditorP2PChannel>(_instanceContext,
                    "SharedTextEditorEndpointP2P");

                var endpointAddress = new EndpointAddress(_channelFactory.Endpoint.Address.ToString());

                _channelFactory.Endpoint.Address = endpointAddress;
                _p2pChannel = _channelFactory.CreateChannel();

                //setup the event handlers for handling online/offline events
                _statusHandler = _p2pChannel.GetProperty<IOnlineStatus>();

                if (_statusHandler != null)
                {
                    _statusHandler.Online += ostat_Online;
                    _statusHandler.Offline += ostat_Offline;
                }

                //call empty method to force connection to mesh
                _p2pChannel.InitializeMesh();
                _editor.UpdateConnectionState(true);
            }
            catch (Exception)
            {
                _editor.UpdateConnectionState(false);
            }
        }
Esempio n. 2
0
		public static void Main ()
		{
			InstanceContext ic = new InstanceContext (new ChatClient ("Marcos"));
			NetPeerTcpBinding nptb = new NetPeerTcpBinding ();
//			NetTcpBinding ntb = new NetTcpBinding ();
//			CustomBinding ntb = new CustomBinding ();
//			ntb.Elements.Add (new TextMessageEncodingBindingElement ());
//			ntb.Elements.Add (new TcpTransportBindingElement ());
			BasicHttpBinding ntb = new BasicHttpBinding ();
//			ntb.Security.Mode = SecurityMode.None;
			nptb.Resolver.Custom.Address = new EndpointAddress ("http://localhost:8080/ChatServer");
			nptb.Resolver.Custom.Binding = ntb;
			nptb.Resolver.Mode = PeerResolverMode.Auto;
//			nptb.Resolver.ReferralPolicy = PeerReferralPolicy.Service;
			nptb.Security.Mode = SecurityMode.None;
//			DuplexChannelFactory<IChatService> factory = 
//				new DuplexChannelFactory<IChatService> (ic, 
//				                                        nptb, 
//				                                        new EndpointAddress ("net.p2p://chatMesh/ChatServer"));
			IChatService channel = 
				DuplexChannelFactory<IChatService>.CreateChannel (ic, 
				                                                  nptb, 
				                                                  new EndpointAddress ("net.p2p://chatMesh/ChatServer"));
//			channel.Open ();
//			Console.WriteLine ("Here!");
			channel.Join ("Marcos");
			// Right here, run the same process separately.
			Console.ReadLine ();
			channel.Leave ("Marcos");
			((IChannel) channel).Close ();
//			factory.Close ();
		}
        public static Binding CreateBinding(string bindingName)
        {
            Binding result = null;

            try
            {
                if (string.Compare(bindingName, typeof(WSHttpBinding).FullName, true) == 0)
                {
                    result = new WSHttpBinding();
                }
                else if (string.Compare(bindingName, typeof(WS2007HttpBinding).FullName, true) == 0)
                {
                    result = new WS2007HttpBinding();
                }
                else if (string.Compare(bindingName, typeof(BasicHttpBinding).FullName, true) == 0)
                {
                    result = new BasicHttpBinding();
                }
                else if (string.Compare(bindingName, typeof(WSDualHttpBinding).FullName, true) == 0)
                {
                    result = new WSDualHttpBinding();
                }
                else if (string.Compare(bindingName, typeof(WS2007FederationHttpBinding).FullName, true) == 0)
                {
                    result = new WS2007FederationHttpBinding();
                }
                else if (string.Compare(bindingName, typeof(WSFederationHttpBinding).FullName, true) == 0)
                {
                    result = new WSFederationHttpBinding();
                }
                else if (string.Compare(bindingName, typeof(NetNamedPipeBinding).FullName, true) == 0)
                {
                    result = new NetNamedPipeBinding();
                }
                else if (string.Compare(bindingName, typeof(NetMsmqBinding).FullName, true) == 0)
                {
                    result = new NetMsmqBinding();
                }
                else if (string.Compare(bindingName, typeof(MsmqIntegrationBinding).FullName, true) == 0)
                {
                    result = new MsmqIntegrationBinding();
                }
                else if (string.Compare(bindingName, typeof(NetTcpBinding).FullName, true) == 0)
                {
                    result = new NetTcpBinding();
                }
                else if (string.Compare(bindingName, typeof(NetPeerTcpBinding).FullName, true) == 0)
                {
                    result = new NetPeerTcpBinding();
                }
            }
            catch
            {
                result = new BasicHttpBinding(BasicHttpSecurityMode.None);
            }

            return result;
        }
Esempio n. 4
0
        // Host the chat instance within this EXE console application.
        public static void Main(string[] args)
        {
            Console.WriteLine("Enter your nickname [default=DefaultName]: ");
            string member = Console.ReadLine();
            Console.WriteLine("Enter the mesh password: "******"") member = "DefaultName";

            // Construct InstanceContext to handle messages on callback interface. 
            // An instance of ChatApp is created and passed to the InstanceContext.
            InstanceContext site = new InstanceContext(new ChatApp());

            // Create the participant with the given endpoint configuration
            // Each participant opens a duplex channel to the mesh
            // participant is an instance of the chat application that has opened a channel to the mesh
            NetPeerTcpBinding binding = new NetPeerTcpBinding("SecureChatBinding");

            ChannelFactory<IChatChannel> cf = new DuplexChannelFactory<IChatChannel>(site, "SecureChatEndpoint");

            //for PeerAuthenticationMode.Password, you need to specify a password
            cf.Credentials.Peer.MeshPassword = password;
            IChatChannel participant = cf.CreateChannel();

            // Retrieve the PeerNode associated with the participant and register for online/offline events
            // PeerNode represents a node in the mesh. Mesh is the named collection of connected nodes.
            IOnlineStatus ostat = participant.GetProperty<IOnlineStatus>();
            ostat.Online += new EventHandler(OnOnline);
            ostat.Offline += new EventHandler(OnOffline);

            // Print instructions to user
            Console.WriteLine("{0} is ready", member);
            Console.WriteLine("Type chat messages after going Online");
            Console.WriteLine("Press q<ENTER> to terminate this instance.");

            // Announce self to other participants
            participant.Join(member);
           
            while (true)
            {
                string line = Console.ReadLine();
                if (line == "q") break;
                participant.Chat(member, line);
            }
            // Leave the mesh and close the proxy
            participant.Leave(member);

            ((IChannel)participant).Close();
            cf.Close();
        }
 public static Binding Resolve(WcfBindingTypes type)
 {
     Binding binding = null;
     switch (type)
     {
         case WcfBindingTypes.BasicHttpBinding:
             binding = new BasicHttpBinding();
             break;
         case WcfBindingTypes.NetTcpBinding:
             binding = new NetTcpBinding();
             break;
         case WcfBindingTypes.NetTcpContextBinding:
             binding = new NetTcpContextBinding();
             break;
         case WcfBindingTypes.WsHttpBinding:
             binding = new WSHttpBinding();
             break;
         case WcfBindingTypes.NetMsmqBinding:
             binding = new NetMsmqBinding();
             break;
         case WcfBindingTypes.NetPeerTcpBinding:
             binding = new NetPeerTcpBinding();
             break;
         case WcfBindingTypes.BasicHttpContextBinding:
             binding = new BasicHttpContextBinding();
             break;
         case WcfBindingTypes.WSHttpContextBinding:
             binding = new WSHttpContextBinding();
             break;
         case WcfBindingTypes.WS2007FederationHttpBinding:
             binding = new WS2007FederationHttpBinding();
             break;
         case WcfBindingTypes.WS2007HttpBinding:
             binding = new WS2007HttpBinding();
             break;
         case WcfBindingTypes.NetNamedPipeBinding:
             binding = new NetNamedPipeBinding();
             break;
         case WcfBindingTypes.WSFederationHttpBinding:
             binding = new WSFederationHttpBinding();
             break;
         case WcfBindingTypes.WSDualHttpBinding:
             binding = new WSDualHttpBinding();
             break;
         default:
             binding = new CustomBinding();
             break;
     }
     return binding;
 }
Esempio n. 6
0
		public void DefaultValues ()
		{
			if (!NetPeerTcpBinding.IsPnrpAvailable)
				Assert.Ignore ("PNRP is not available."); // yes, we actually don't test it.

			var n = new NetPeerTcpBinding ();
			Assert.AreEqual (EnvelopeVersion.Soap12, n.EnvelopeVersion, "#1");
			Assert.IsNull (n.ListenIPAddress, "#2");
			Assert.AreEqual (0x10000, n.MaxReceivedMessageSize, "#3");
			Assert.AreEqual (0, n.Port, "#4");
			Assert.IsNotNull (n.ReaderQuotas, "#5");

			var bec = n.CreateBindingElements ();
			Assert.IsNotNull (bec.Find<PnrpPeerResolverBindingElement> (), "#bec0");
			Assert.IsNotNull (bec.Find<BinaryMessageEncodingBindingElement> (), "#bec1");
			Assert.AreEqual (3, bec.Count, "#bec2");

			var tr = bec.Find<PeerTransportBindingElement> ();
			Assert.IsNotNull (tr, "#tr1");
		}
Esempio n. 7
0
#pragma warning disable CS0618
        private static void GetNetPeerTcpBindingDetails(NetPeerTcpBinding binding, ref string name, ref string mode, ref string credentialType)
        {
            name = GetBindingName <NetPeerTcpBinding>(binding);

            PeerSecuritySettings peerSecuritySettings = binding.Security;

            mode = peerSecuritySettings?.Mode.ToString();
            switch (peerSecuritySettings?.Mode)
            {
            case SecurityMode.None:
                credentialType = "N/A";
                break;

            case SecurityMode.Transport:
            case SecurityMode.TransportWithMessageCredential:
            case SecurityMode.Message:
                credentialType = peerSecuritySettings.Transport?.CredentialType.ToString();
                break;
            }
        }
Esempio n. 8
0
	public static void Main ()
	{
		var binding = new NetPeerTcpBinding ();
		binding.Resolver.Mode = PeerResolverMode.Custom;
		binding.Resolver.Custom.Address = new EndpointAddress ("net.tcp://localhost:8086");
		var tcp = new NetTcpBinding () { TransactionFlow = false };
		tcp.Security.Mode = SecurityMode.None;
		binding.Resolver.Custom.Binding = tcp;

		binding.Security.Mode = SecurityMode.None;
		IFooChannel proxy = new DuplexChannelFactory<IFooChannel> (
			new Foo (),
			binding,
			new EndpointAddress ("net.p2p://samplemesh/SampleService")
			).CreateChannel ();
		proxy.Open ();
		proxy.SendMessage ("TEST FOR ECHO");
		Console.WriteLine (proxy.SessionId);
		Console.WriteLine ("type [CR] to quit");
		Console.ReadLine ();
	}
Esempio n. 9
0
		public void DefaultValuesForCustom ()
		{
			var n = new NetPeerTcpBinding ();
			n.Resolver.Mode = PeerResolverMode.Custom;
			n.Resolver.Custom.Resolver = new DummyResolver ();

			Assert.AreEqual (EnvelopeVersion.Soap12, n.EnvelopeVersion, "#1");
			Assert.IsNull (n.ListenIPAddress, "#2");
			Assert.AreEqual (0x10000, n.MaxReceivedMessageSize, "#3");
			Assert.AreEqual (0, n.Port, "#4");
			Assert.IsNotNull (n.ReaderQuotas, "#5");

			Assert.IsFalse (((IBindingRuntimePreferences) n).ReceiveSynchronously, "#6");

			var bec = n.CreateBindingElements ();
			Assert.IsNotNull (bec.Find<PeerCustomResolverBindingElement> (), "#bec0");
			Assert.IsNotNull (bec.Find<BinaryMessageEncodingBindingElement> (), "#bec1");
			Assert.AreEqual (3, bec.Count, "#bec2");

			var tr = bec.Find<PeerTransportBindingElement> ();
			Assert.IsNotNull (tr, "#tr1");
		}
Esempio n. 10
0
 private void btnStart_Click(object sender, EventArgs e)
 {
     try
     {
         Binding bind = new NetPeerTcpBinding();
         cprs = new CustomPeerResolverService();
         cprs.RefreshInterval = TimeSpan.FromSeconds(5);
         host = new ServiceHost(cprs, new Uri[] { new Uri("net.tcp://127.0.0.1/ChatServer") });
         cprs.ControlShape = true;
         cprs.Open();
         host.Open(TimeSpan.FromDays(1000000));
         lblMessage.Text = "Server started successfully.";
     }
     catch (Exception ex)
     {
         MessageBox.Show(ex.ToString());
     }
     finally
     {
         btnStart.Enabled = false;
         btnStop.Enabled = true;
     }
 }
Esempio n. 11
0
        public void ClientRespond(string request, int channel, string addr, string port)
        {
            NameValueCollection settings =
            ConfigurationManager.GetSection("listenAddressGroup/listenAddress")
            as System.Collections.Specialized.NameValueCollection;

            string address = "";
            if (settings != null)
            {
                address = settings.AllKeys[0];
            }
            string[] res = address.Split(new string[] { ":" }, StringSplitOptions.None);
            NetPeerTcpBinding binding = new NetPeerTcpBinding("Wimpy");
            if ((port != "") && String.Compare(address, addr + ":" + port) == 0)
            {
                _channel = new ChannelFactory<IBackend>(binding, "net.p2p://" + addr + ":" + port + "/FileService").CreateChannel();
            }
            else if ((port == "") && (res.Length == 1) && String.Compare(address, addr) == 0)
            {
                _channel = new ChannelFactory<IBackend>(binding, "net.p2p://" + addr + "/FileService").CreateChannel();
            }
            _client = new DiffieHellman(64).GenerateResponse(request);
            _channel.ServerHandle(_client.ToString(), channel);
        }
        internal static bool TryCreate(BindingElementCollection elements, out Binding binding)
        {
            binding = null;
            if (elements.Count != 3)
            {
                return(false);
            }
            PeerResolverBindingElement          element   = null;
            PeerTransportBindingElement         transport = null;
            BinaryMessageEncodingBindingElement encoding  = null;

            foreach (BindingElement element4 in elements)
            {
                if (element4 is TransportBindingElement)
                {
                    transport = element4 as PeerTransportBindingElement;
                }
                else if (element4 is BinaryMessageEncodingBindingElement)
                {
                    encoding = element4 as BinaryMessageEncodingBindingElement;
                }
                else if (element4 is PeerResolverBindingElement)
                {
                    element = element4 as PeerResolverBindingElement;
                }
                else
                {
                    return(false);
                }
            }
            if (transport == null)
            {
                return(false);
            }
            if (encoding == null)
            {
                return(false);
            }
            if (element == null)
            {
                return(false);
            }
            NetPeerTcpBinding binding2 = new NetPeerTcpBinding();

            binding2.InitializeFrom(transport, encoding);
            if (!binding2.IsBindingElementsMatch(transport, encoding))
            {
                return(false);
            }
            PeerCustomResolverBindingElement element5 = element as PeerCustomResolverBindingElement;

            if (element5 != null)
            {
                binding2.Resolver.Custom.Address  = element5.Address;
                binding2.Resolver.Custom.Binding  = element5.Binding;
                binding2.Resolver.Custom.Resolver = element5.CreatePeerResolver();
            }
            else if ((element is PnrpPeerResolverBindingElement) && IsPnrpAvailable)
            {
                binding2.Resolver.Mode = PeerResolverMode.Pnrp;
            }
            binding = binding2;
            return(true);
        }
 internal static bool TryCreate(BindingElementCollection elements, out Binding binding)
 {
     binding = null;
     if (elements.Count != 3)
     {
         return false;
     }
     PeerResolverBindingElement element = null;
     PeerTransportBindingElement transport = null;
     BinaryMessageEncodingBindingElement encoding = null;
     foreach (BindingElement element4 in elements)
     {
         if (element4 is TransportBindingElement)
         {
             transport = element4 as PeerTransportBindingElement;
         }
         else if (element4 is BinaryMessageEncodingBindingElement)
         {
             encoding = element4 as BinaryMessageEncodingBindingElement;
         }
         else if (element4 is PeerResolverBindingElement)
         {
             element = element4 as PeerResolverBindingElement;
         }
         else
         {
             return false;
         }
     }
     if (transport == null)
     {
         return false;
     }
     if (encoding == null)
     {
         return false;
     }
     if (element == null)
     {
         return false;
     }
     NetPeerTcpBinding binding2 = new NetPeerTcpBinding();
     binding2.InitializeFrom(transport, encoding);
     if (!binding2.IsBindingElementsMatch(transport, encoding))
     {
         return false;
     }
     PeerCustomResolverBindingElement element5 = element as PeerCustomResolverBindingElement;
     if (element5 != null)
     {
         binding2.Resolver.Custom.Address = element5.Address;
         binding2.Resolver.Custom.Binding = element5.Binding;
         binding2.Resolver.Custom.Resolver = element5.CreatePeerResolver();
     }
     else if ((element is PnrpPeerResolverBindingElement) && IsPnrpAvailable)
     {
         binding2.Resolver.Mode = PeerResolverMode.Pnrp;
     }
     binding = binding2;
     return true;
 }
Esempio n. 14
0
        internal static bool TryCreate(BindingElementCollection elements, out Binding binding)
        {
            binding = null;
            if (elements.Count != 3)
            {
                return(false);
            }

            PeerResolverBindingElement          resolver  = null;
            PeerTransportBindingElement         transport = null;
            BinaryMessageEncodingBindingElement encoding  = null;

            foreach (BindingElement element in elements)
            {
                if (element is TransportBindingElement)
                {
                    transport = element as PeerTransportBindingElement;
                }
                else if (element is BinaryMessageEncodingBindingElement)
                {
                    encoding = element as BinaryMessageEncodingBindingElement;
                }
                else if (element is PeerResolverBindingElement)
                {
                    resolver = element as PeerResolverBindingElement;
                }
                else
                {
                    return(false);
                }
            }

            if (transport == null)
            {
                return(false);
            }

            if (encoding == null)
            {
                return(false);
            }

            if (resolver == null)
            {
                return(false);
            }

            NetPeerTcpBinding netPeerTcpBinding = new NetPeerTcpBinding();

            netPeerTcpBinding.InitializeFrom(transport, encoding);
            if (!netPeerTcpBinding.IsBindingElementsMatch(transport, encoding))
            {
                return(false);
            }

            PeerCustomResolverBindingElement customResolver = resolver as PeerCustomResolverBindingElement;

            if (customResolver != null)
            {
                netPeerTcpBinding.Resolver.Custom.Address  = customResolver.Address;
                netPeerTcpBinding.Resolver.Custom.Binding  = customResolver.Binding;
                netPeerTcpBinding.Resolver.Custom.Resolver = customResolver.CreatePeerResolver();
            }
            else if (resolver is PnrpPeerResolverBindingElement)
            {
                if (NetPeerTcpBinding.IsPnrpAvailable)
                {
                    netPeerTcpBinding.Resolver.Mode = PeerResolverMode.Pnrp;
                }
            }
            binding = netPeerTcpBinding;
            return(true);
        }
        /// <summary>
        /// 
        /// </summary>
        private void registerPeerChannel(string id)
        {
            XmlDictionaryReaderQuotas quotas = new XmlDictionaryReaderQuotas();
             quotas.MaxArrayLength = int.MaxValue;
             quotas.MaxBytesPerRead = int.MaxValue;
             quotas.MaxDepth = int.MaxValue;
             quotas.MaxNameTableCharCount = int.MaxValue;
             quotas.MaxStringContentLength = int.MaxValue;

             NetPeerTcpBinding myBinding = new NetPeerTcpBinding();
             myBinding.ReaderQuotas = quotas;
             myBinding.Resolver.Mode = System.ServiceModel.PeerResolvers.PeerResolverMode.Pnrp;

             if (parameters.UseTLS)
             {
            myBinding.Security.Mode = SecurityMode.Transport;
            myBinding.Security.Transport.CredentialType = PeerTransportCredentialType.Password;
             }
             else
             {
            myBinding.Security.Mode = SecurityMode.None;
             }

             // if the listening address is specified, use it
             if (parameters.Ip != null)
             {
            this.doInfo(this, new ScallopInfoEventArgs("Ignored listening address"));
            /*
            this.doInfo(this, new ScallopInfoEventArgs("Listening on ip " + parameters.Ip.ToString()));
            myBinding.ListenIPAddress = parameters.Ip;
            */
             }

             EndpointAddress myAddress = new EndpointAddress("net.p2p://Scallop_" + this.Version + "_" + parameters.NetworkName + "/");

             this.factory = new DuplexChannelFactory<IPeerChannelChannel>(new InstanceContext(this), myBinding, myAddress);
             this.factory.Faulted += this.factory_faulted;
             this.factory.Closed += this.factory_faulted;

             if (parameters.UseTLS)
            this.factory.Credentials.Peer.MeshPassword = parameters.TLSPassword;

             this.chan = factory.CreateChannel();

             ScallopMessageFilter msgFilter = new ScallopMessageFilter(id);
             peer = chan.GetProperty<PeerNode>();
             peer.Offline += new EventHandler(peer_Offline);
             peer.Online += new EventHandler(peer_Online);
             peer.MessagePropagationFilter = msgFilter;

             this.chan.Open();

             this.chan.PCJoin(this.id);
             this.registered = true;

             this.id = id;

             //if(peer.IsOnline)
             //   this.doStateChanged(this, new ScallopNetworkStatusChangedEventArgs(ScallopNetworkState.Online, null, "Online"));
        }
        internal static bool TryCreate(BindingElementCollection elements, out Binding binding)
        {
            binding = null;
            if (elements.Count != 3)
                return false;

            PeerResolverBindingElement resolver = null;
            PeerTransportBindingElement transport = null;
            BinaryMessageEncodingBindingElement encoding = null;

            foreach (BindingElement element in elements)
            {
                if (element is TransportBindingElement)
                    transport = element as PeerTransportBindingElement;
                else if (element is BinaryMessageEncodingBindingElement)
                    encoding = element as BinaryMessageEncodingBindingElement;
                else if (element is PeerResolverBindingElement)
                    resolver = element as PeerResolverBindingElement;
                else
                    return false;
            }

            if (transport == null)
                return false;

            if (encoding == null)
                return false;

            if (resolver == null)
                return false;

            NetPeerTcpBinding netPeerTcpBinding = new NetPeerTcpBinding();
            netPeerTcpBinding.InitializeFrom(transport, encoding);
            if (!netPeerTcpBinding.IsBindingElementsMatch(transport, encoding))
                return false;

            PeerCustomResolverBindingElement customResolver = resolver as PeerCustomResolverBindingElement;
            if (customResolver != null)
            {
                netPeerTcpBinding.Resolver.Custom.Address = customResolver.Address;
                netPeerTcpBinding.Resolver.Custom.Binding = customResolver.Binding;
                netPeerTcpBinding.Resolver.Custom.Resolver = customResolver.CreatePeerResolver();
            }
            else if (resolver is PnrpPeerResolverBindingElement)
            {

                if (NetPeerTcpBinding.IsPnrpAvailable)
                    netPeerTcpBinding.Resolver.Mode = PeerResolverMode.Pnrp;
            }
            binding = netPeerTcpBinding;
            return true;
        }
Esempio n. 17
0
File: Service.cs Progetto: rmc00/gsf
        /// <summary>
        /// Creates a <see cref="Binding"/> based on the specified <paramref name="address"/>.
        /// </summary>
        /// <param name="address">The URI that is used to determine the type of <see cref="Binding"/> to be created.</param>
        /// <param name="enableSecurity">A boolean value that indicated whether security is to be enabled on the <see cref="Binding"/>.</param>
        /// <returns>An <see cref="Binding"/> object if a valid <paramref name="address"/> is specified; otherwise null.</returns>
        /// <remarks>
        /// This list shows all valid address schemes that can be specified in the <paramref name="address"/>:
        /// <list type="table">
        ///     <listheader>
        ///         <term>Address Scheme</term>
        ///         <description>Usage</description>
        ///     </listheader>
        ///     <item>
        ///         <term><b>http://</b> or <b>http.soap11://</b></term>
        ///         <description>An <paramref name="address"/> of <b>http.soap11://localhost:2929</b> will create an <see cref="BasicHttpBinding"/> and update the <paramref name="address"/> to <b>http://localhost:2929</b>.</description>
        ///     </item>
        ///     <item>
        ///         <term><b>http.soap12://</b></term>
        ///         <description>An <paramref name="address"/> of <b>http.soap12://localhost:2929</b> will create an <see cref="WSHttpBinding"/> and update the <paramref name="address"/> to <b>http://localhost:2929</b>.</description>
        ///     </item>
        ///     <item>
        ///         <term><b>http.duplex://</b></term>
        ///         <description>An <paramref name="address"/> of <b>http.duplex://localhost:2929</b> will create an <see cref="WSDualHttpBinding"/> and update the <paramref name="address"/> to <b>http://localhost:2929</b>.</description>
        ///     </item>
        ///     <item>
        ///         <term><b>http.rest://</b></term>
        ///         <description>An <paramref name="address"/> of <b>http.rest://localhost:2929</b> will create an <see cref="WebHttpBinding"/> and update the <paramref name="address"/> to <b>http://localhost:2929</b>.</description>
        ///     </item>
        ///     <item>
        ///         <term><b>net.tcp://</b></term>
        ///         <description>An <paramref name="address"/> of <b>net.tcp://localhost:2929</b> will create an <see cref="NetTcpBinding"/> and leave the <paramref name="address"/> unchanged.</description>
        ///     </item>
        ///     <item>
        ///         <term><b>net.p2p://</b></term>
        ///         <description>An <paramref name="address"/> of <b>net.p2p://localhost:2929</b> will create an <see cref="NetPeerTcpBinding"/> and leave the <paramref name="address"/> unchanged.</description>
        ///     </item>
        ///     <item>
        ///         <term><b>net.pipe://</b></term>
        ///         <description>An <paramref name="address"/> of <b>net.pipe://localhost:2929</b> will create an <see cref="NetNamedPipeBinding"/> and leave the <paramref name="address"/> unchanged.</description>
        ///     </item>
        ///     <item>
        ///         <term><b>net.msmq://</b></term>
        ///         <description>An <paramref name="address"/> of <b>net.msmq://localhost:2929</b> will create an <see cref="NetMsmqBinding"/> and leave the <paramref name="address"/> unchanged.</description>
        ///     </item>
        /// </list>
        /// <para>
        /// The <paramref name="enableSecurity"/> parameter value is ignored Mono deployments since security bindings are not implemented.
        /// </para>
        /// </remarks>
        public static Binding CreateServiceBinding(ref string address, bool enableSecurity)
        {
            address = address.Trim();
            if (string.IsNullOrEmpty(address))
                return null;

            int index = address.IndexOf("://");
            string scheme = address.Substring(0, index >= 0 ? index : address.Length);
            switch (scheme.ToLower())
            {
                case "http":
                case "http.soap11":
                    // Format address.
                    address = address.Replace("http.soap11", "http");
                    // Create binding.
                    BasicHttpBinding soap11Binding = new BasicHttpBinding();

#if !MONO
                    if (enableSecurity)
                    {
                        // Enable security.
                        soap11Binding.Security.Mode = BasicHttpSecurityMode.TransportCredentialOnly;
                        soap11Binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Windows;
                    }
                    else
                    {
                        // Disable security.
                        soap11Binding.Security.Mode = BasicHttpSecurityMode.None;
                        soap11Binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.None;
                    }
#endif

                    return soap11Binding;
                case "http.soap12":
                    // Format address.
                    address = address.Replace("http.soap12", "http");
                    // Create binding.
                    WSHttpBinding soap12Binding = new WSHttpBinding();

#if !MONO
                    if (enableSecurity)
                    {
                        // Enable security.
                        soap12Binding.Security.Mode = SecurityMode.Transport;
                        soap12Binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Windows;
                    }
                    else
                    {
                        // Disable security.
                        soap12Binding.Security.Mode = SecurityMode.None;
                        soap12Binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.None;
                    }
#endif

                    return soap12Binding;
                case "http.duplex":
                    // Format address.
                    address = address.Replace("http.duplex", "http");
                    // Create binding.
                    WSDualHttpBinding duplexBinding = new WSDualHttpBinding();

#if !MONO
                    if (enableSecurity)
                    {
                        // Enable security.
                        duplexBinding.Security.Mode = WSDualHttpSecurityMode.Message;
                    }
                    else
                    {
                        // Disable security.
                        duplexBinding.Security.Mode = WSDualHttpSecurityMode.None;
                    }
#endif

                    return duplexBinding;
                case "http.rest":
                    // Format address.
                    address = address.Replace("http.rest", "http");
                    // Create binding.
                    WebHttpBinding restBinding = new WebHttpBinding();

#if !MONO
                    if (enableSecurity)
                    {
                        // Enable security.
                        restBinding.Security.Mode = WebHttpSecurityMode.TransportCredentialOnly;
                        restBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Windows;
                    }
                    else
                    {
                        // Disable security.
                        restBinding.Security.Mode = WebHttpSecurityMode.None;
                        restBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.None;
                    }
#endif

                    return restBinding;
                case "net.tcp":
                    // Create binding.
                    NetTcpBinding tcpBinding = new NetTcpBinding();

#if !MONO
                    if (enableSecurity)
                    {
                        // Enable security.
                        tcpBinding.Security.Mode = SecurityMode.Transport;
                        tcpBinding.Security.Transport.ClientCredentialType = TcpClientCredentialType.Windows;
                    }
                    else
                    {
                        // Disable sercurity.
                        tcpBinding.Security.Mode = SecurityMode.None;
                        tcpBinding.Security.Transport.ClientCredentialType = TcpClientCredentialType.None;
                    }
#endif

                    return tcpBinding;
                case "net.p2p":
                    // Create binding.
#pragma warning disable 612, 618
                    NetPeerTcpBinding p2pBinding = new NetPeerTcpBinding();

#if !MONO
                    if (enableSecurity)
                    {
                        // Enable security.
                        p2pBinding.Security.Mode = SecurityMode.Transport;
                    }
                    else
                    {
                        // Disable security.
                        p2pBinding.Security.Mode = SecurityMode.None;
                    }
#endif

                    return p2pBinding;
                case "net.pipe":
                    // Create binding.
                    NetNamedPipeBinding pipeBinding = new NetNamedPipeBinding();

#if !MONO
                    if (enableSecurity)
                    {
                        // Enable security.
                        pipeBinding.Security.Mode = NetNamedPipeSecurityMode.Transport;
                    }
                    else
                    {
                        // Disable security.
                        pipeBinding.Security.Mode = NetNamedPipeSecurityMode.None;
                    }
#endif

                    return pipeBinding;
                case "net.msmq":
                    // Create binding.
                    NetMsmqBinding msmqBinding = new NetMsmqBinding();

#if !MONO
                    if (enableSecurity)
                    {
                        // Enable security.
                        msmqBinding.Security.Mode = NetMsmqSecurityMode.Transport;
                    }
                    else
                    {
                        // Disable security.
                        msmqBinding.Security.Mode = NetMsmqSecurityMode.None;
                    }
#endif

                    return msmqBinding;
                default:
                    return null;
            }
        }
Esempio n. 18
0
        // Host the receiver within this EXE console application.
        public static void Main()
        {
            string recognizedPublisherName = ConfigurationManager.AppSettings["publisherQName"];

            ServiceHost receiver = new ServiceHost(new BroadcastReceiver());

            //this settings specifies that only messages signed with above cert should be accepted.
            NetPeerTcpBinding binding = new NetPeerTcpBinding("Binding1");
            
            // set peer credentials
            X509Certificate2 certificate = GetCertificate(StoreName.TrustedPeople, StoreLocation.CurrentUser, recognizedPublisherName, X509FindType.FindBySubjectDistinguishedName);
            receiver.Credentials.Peer.MessageSenderAuthentication.CertificateValidationMode = X509CertificateValidationMode.Custom;
            receiver.Credentials.Peer.MessageSenderAuthentication.CustomCertificateValidator = new PublisherValidator(certificate);

            // Open the ServiceHostBase to create listeners and start listening for messages.
            receiver.Open();

            // Retrieve the PeerNode associated with the receiver and register for online/offline events
            // PeerNode represents a node in the mesh. Mesh is the named collection of connected nodes.

            // use the first base address.
            string baseAddress = receiver.BaseAddresses[0].ToString();

            EndpointAddress lookFor = new EndpointAddress(baseAddress + "announcements");
            for (int i=0; i<receiver.ChannelDispatchers.Count; ++i)
            {
                ChannelDispatcher channelDispatcher = receiver.ChannelDispatchers[i] as ChannelDispatcher;
                if (channelDispatcher != null)
                {
                    for (int j=0; j<channelDispatcher.Endpoints.Count; ++j)
                    {
                        EndpointDispatcher endpointDispatcher = channelDispatcher.Endpoints[j];
                        if (endpointDispatcher.EndpointAddress == lookFor)
                        {
                            IOnlineStatus ostat = (IOnlineStatus)channelDispatcher.Listener.GetProperty<IOnlineStatus>();
                            if (ostat != null)
                            {
                                ostat.Online += OnOnline;
                                ostat.Offline += OnOffline;
                                if (ostat.IsOnline)
                                {
                                    Console.WriteLine("**  Online");
                                }
                            }
                        }
                    }
                }
            }
            
            // The receiver can now receive broadcast announcements
            Console.WriteLine("**  The receiver is ready");
            Console.WriteLine("Press <ENTER> to terminate receiver.");
            Console.ReadLine();

            // Close the ServiceHostBase to shutdown the receiver
            receiver.Close();
        }
Esempio n. 19
0
 /// <summary>
 /// 
 /// </summary>
 /// <param name="bindingType"></param>
 /// <param name="setting"></param>
 /// <returns></returns>
 public Binding CreateBinding(BindingType bindingType, BindingBehaviorSetting setting)
 {
     Binding bindinginstance = null;
     switch (bindingType)
     {
         case BindingType.BasicHttpBinding:
             BasicHttpBinding basicHttp = new BasicHttpBinding();
             basicHttp.MaxReceivedMessageSize = MaxReceivedSize;
             bindinginstance = basicHttp;
             break;
         case BindingType.NetNamedPipeBinding:
             NetNamedPipeBinding wsPipe = new NetNamedPipeBinding();
             wsPipe.MaxReceivedMessageSize = MaxReceivedSize;
             bindinginstance = wsPipe;
             break;
         case BindingType.NetPeerTcpBinding:
             NetPeerTcpBinding wsPeerTcp = new NetPeerTcpBinding();
             wsPeerTcp.MaxReceivedMessageSize = MaxReceivedSize;
             bindinginstance = wsPeerTcp;
             break;
         case BindingType.NetTcpBinding:
             NetTcpBinding wsTcp = new NetTcpBinding();
             wsTcp.MaxReceivedMessageSize = MaxReceivedSize;
             wsTcp.ReliableSession.Enabled = true;
             wsTcp.ReliableSession.InactivityTimeout = setting.InactivityTimeout;
             wsTcp.Security.Mode = SecurityMode.None;
             wsTcp.OpenTimeout = setting.ConnectTimeout;
             wsTcp.CloseTimeout = setting.ConnectTimeout;
             wsTcp.SendTimeout = setting.SendTimeout;
             wsTcp.ReceiveTimeout = setting.ReceiveTimeout;
             bindinginstance = wsTcp;
             break;
         case BindingType.WsDualHttpBinding:
             WSDualHttpBinding wsDual = new WSDualHttpBinding();
             wsDual.MaxReceivedMessageSize = MaxReceivedSize;
             bindinginstance = wsDual;
             break;
         case BindingType.WsFederationHttpBinding:
             WSFederationHttpBinding wsFederation = new WSFederationHttpBinding();
             wsFederation.MaxReceivedMessageSize = MaxReceivedSize;
             bindinginstance = wsFederation;
             break;
         case BindingType.WsHttpBinding:
             WSHttpBinding wsHttp = new WSHttpBinding(SecurityMode.None);
             wsHttp.MaxReceivedMessageSize = MaxReceivedSize;
             wsHttp.Security.Message.ClientCredentialType = MessageCredentialType.Windows;
             wsHttp.Security.Transport.ClientCredentialType = HttpClientCredentialType.Windows;
             bindinginstance = wsHttp;
             break;
         default:
             throw new ArgumentOutOfRangeException("bindingType");
     }
     return bindinginstance;
 }
Esempio n. 20
0
        public void ServerSend(string request)
        {
            if (counter == 0)
            {
                counter++;
                ClientSection clientSection = (ClientSection)WebConfigurationManager.GetSection("system.serviceModel/client");
                NetPeerTcpBinding binding = new NetPeerTcpBinding("Wimpy");

                string port = "";
                for (int i = 0; i < clientSection.Endpoints.Count; i++)
                {
                    string[] chars = new string[] { "//", "/", ":" };
                    string address = clientSection.Endpoints[i].Address.ToString();
                    string[] res = address.Split(chars, StringSplitOptions.None);
                    if (res.Length > 4)
                        port = res[3];
                    channels.Add(new ChannelFactory<IBackend>(binding, address).CreateChannel());
                }

                DiffieHellman.keys = new List<byte[]>();
                for (int i = 0; i < channels.Count; i++)
                {
                    DiffieHellman.keys.Add(new byte[8]);
                }
                for (int i = 0; i < channels.Count; i++)
                {
                    channels[i].ClientRespond(request, i, GetLocalIPAddress(), port);
                }
            }
            else counter = 0;
        }