private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            string ipAdress = ConfigurationManager.AppSettings["ipAdress"];

            new System.Threading.Thread(() =>
            {
                ChatToClient server             = new ChatToClient();
                server.ReceiveMsgEvent         += server_ReceiveMsgEvent;
                server.ReceiveImageEvent       += server_ReceiveImageEvent;
                server.ReceiveFriendListEvent  += GetOrUpdateFriendList;
                InstanceContext context         = new InstanceContext(server);
                WSDualHttpBinding bingding      = new WSDualHttpBinding();
                bingding.MaxReceivedMessageSize = Int32.MaxValue;
                bingding.MaxBufferPoolSize      = Int32.MaxValue;
                bingding.OpenTimeout            = new TimeSpan(0, 20, 0);
                bingding.SendTimeout            = new TimeSpan(0, 20, 0);
                //必须加上,否则传输大文件有问题..
                bingding.ReaderQuotas.MaxDepth = int.MaxValue;
                bingding.ReaderQuotas.MaxStringContentLength = int.MaxValue;
                bingding.ReaderQuotas.MaxArrayLength         = int.MaxValue;
                bingding.ReaderQuotas.MaxBytesPerRead        = int.MaxValue;
                bingding.ReaderQuotas.MaxNameTableCharCount  = int.MaxValue;

                //安全性
                bingding.UseDefaultWebProxy = false;
                bingding.Security.Message.ClientCredentialType = MessageCredentialType.None;
                bingding.Security.Mode = WSDualHttpSecurityMode.None;

                factory = new DuplexChannelFactory <IChatToServer>(context, bingding, new EndpointAddress(ipAdress));
                foreach (OperationDescription op in factory.Endpoint.Contract.Operations)
                {
                    DataContractSerializerOperationBehavior dataContractBehavior = op.Behaviors.Find <DataContractSerializerOperationBehavior>() as DataContractSerializerOperationBehavior;
                    if (dataContractBehavior != null)
                    {
                        dataContractBehavior.MaxItemsInObjectGraph = Int32.MaxValue;
                    }
                }
                try
                {
                    client = factory.CreateChannel();
                    client.Login(UserName);
                    client.GetFriendList();
                    UpdateText(DateTime.Now.ToString() + "  已经与服务器连接..", Colors.Gray, true);
                    this.Dispatcher.Invoke(new Action(() =>
                    {
                        this.loadingFrame.Visibility = System.Windows.Visibility.Collapsed;
                        this.mainGrid.Visibility     = System.Windows.Visibility.Visible;
                    }));
                }
                catch (Exception ee)
                {
                    UpdateText(DateTime.Now.ToString() + "  " + ee.Message + "\r\n请重启客户端重新来连接", Colors.Red, true);
                    this.Dispatcher.Invoke(new Action(() =>
                    {
                        this.loadingFrame.Visibility = System.Windows.Visibility.Collapsed;
                        this.mainGrid.Visibility     = System.Windows.Visibility.Visible;
                    }));
                }
            }).Start();
        }
        private void InitializeClient()
        {
            if (_proxy != null)
            {
                try
                {
                    _proxy.Close();
                }
                catch
                {
                    _proxy.Abort();
                }
            }

            var callback = new AgentCommunicationCallback();

            callback.ServiceCallbackEvent += HandleServiceCallbackEvent;

            var instanceContext = new InstanceContext(callback);
            var dualHttpBinding = new WSDualHttpBinding(WSDualHttpSecurityMode.None);
            var endpointAddress = new EndpointAddress(ServiceEndpointUri);

            _proxy = new AgentCommunicationServiceClient(instanceContext, dualHttpBinding, endpointAddress);
            _proxy.Open();
            _proxy.Subscribe();
        }
        private void Run()
        {
            try
            {
                WSDualHttpBinding binding = new WSDualHttpBinding();
                binding.OpenTimeout    = new TimeSpan(1, 0, 0);
                binding.CloseTimeout   = new TimeSpan(1, 0, 0);
                binding.SendTimeout    = new TimeSpan(1, 0, 0);
                binding.ReceiveTimeout = new TimeSpan(1, 0, 0);
                selftHost.AddServiceEndpoint(typeof(ICracker), binding, "PasswordCracker");

                ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
                smb.HttpGetEnabled = true;

                selftHost.Description.Behaviors.Find <ServiceDebugBehavior>().IncludeExceptionDetailInFaults = true;
                selftHost.Description.Behaviors.Add(smb);

                selftHost.Open();
            }
            catch (CommunicationException ce)
            {
                MessageBoxResult result = MessageBox.Show(ce.Message, "Confirmation", MessageBoxButton.YesNo, MessageBoxImage.Question);
                selftHost.Abort();
                System.Windows.Application.Current.Shutdown();
            }
        }
Beispiel #4
0
        static void Main(string[] args)
        {
            Console.Write("Input Endpoint: ");
            string InputEndpoint = Console.ReadLine();
            // WCF Binding
            var binding = new WSDualHttpBinding();

            // For Duplex Callback
            InstanceContext CallbackContext = new InstanceContext(new ChatClient());

            // Duplex Initialize
            DuplexChannelFactory <IChatService> Channel = new DuplexChannelFactory <IChatService>(CallbackContext, binding);
            EndpointAddress Endpoint = new EndpointAddress(InputEndpoint);

            // Create Duplex Channel
            var Service = Channel.CreateChannel(Endpoint);

            Console.Write("Enter Username: "******"Enter Message: ");
                string Message = Console.ReadLine();
                Service.SendMessage(Username, Message);
            }
        }
        internal static void ConfigureBusinessToBusiness(Collection <ServiceEndpoint> endpoints)
        {
            foreach (ServiceEndpoint endpoint in endpoints)
            {
                Binding binding = endpoint.Binding;

                if (binding is BasicHttpBinding)
                {
                    BasicHttpBinding basicBinding = (BasicHttpBinding)binding;
                    basicBinding.Security.Mode = BasicHttpSecurityMode.Message;
                    basicBinding.Security.Message.ClientCredentialType = BasicHttpMessageCredentialType.Certificate;
                    continue;
                }
                if (binding is WSHttpBinding)
                {
                    WSHttpBinding wsBinding = (WSHttpBinding)binding;
                    wsBinding.Security.Mode = SecurityMode.Message;
                    wsBinding.Security.Message.ClientCredentialType = MessageCredentialType.Certificate;
                    continue;
                }
                if (binding is WSDualHttpBinding)
                {
                    WSDualHttpBinding wsDualBinding = (WSDualHttpBinding)binding;
                    wsDualBinding.Security.Mode = WSDualHttpSecurityMode.Message;
                    wsDualBinding.Security.Message.ClientCredentialType = MessageCredentialType.Certificate;
                    continue;
                }
                if (binding is CustomBinding && endpoint.Contract.ContractType == typeof(IMetadataExchange))
                {
                    Trace.WriteLine("No declarative security for MEX endpoint when adding it programmatically");
                    continue;
                }
                throw new InvalidOperationException(binding.GetType() + "is unsupprted with ServiceSecurity.BusinessToBusiness");
            }
        }
        static void Main(string[] args)
        {
            InstanceContext      site   = new InstanceContext(null, new Client());
            SampleContractClient client = new SampleContractClient(site);

            //create a unique callback address so multiple clients can run on one machine
            WSDualHttpBinding binding = (WSDualHttpBinding)client.Endpoint.Binding;
            string            clientcallbackaddress = binding.ClientBaseAddress.AbsoluteUri;

            clientcallbackaddress    += Guid.NewGuid().ToString();
            binding.ClientBaseAddress = new Uri(clientcallbackaddress);

            //Subscribe.
            Console.WriteLine("Subscribing");
            var marketData = new MarketData {
                businessDate = DateTime.Now, StockPrice = 1000
            };

            client.Subscribe();
            //Console.Write("Publishing: ");
            //Console.WriteLine("PriceChange(businessDate {0}, price {1})", marketData.businessDate.ToShortDateString(), marketData.StockPrice.ToString("C"));
            client.PublishPriceChange(new MarketData {
                businessDate = DateTime.Now, StockPrice = 1000
            });

            Console.WriteLine();
            Console.WriteLine("Press ENTER to unsubscribe and shut down client");
            Console.ReadLine();

            Console.WriteLine("Unsubscribing");
            client.Unsubscribe();

            //Closing the client gracefully closes the connection and cleans up resources
            client.Close();
        }
        public void CreateMessageChannel(string url)
        {
            int                           tryCount = 0;
            int                           maxCount = 10;
            EndpointAddress               address  = new EndpointAddress(url);
            WSDualHttpBinding             binding  = new WSDualHttpBinding();
            ChannelFactory <ICommService> factory
                = new ChannelFactory <ICommService>(binding, address);

            channel = factory.CreateChannel();
            while (true)
            {
                try
                {
                    channel  = factory.CreateChannel();
                    tryCount = 0;
                    break;
                }
                catch (Exception ex)
                {
                    if (++tryCount <= maxCount)
                    {
                        Thread.Sleep(500);
                    }
                    else
                    {
                        throw ex;
                    }
                }
            }
        }
Beispiel #8
0
        private void InitializeProxy()
        {
            if (this.rbTcpBinding.Checked)
            {
                m_proxy = new localhost.HelloIndigoServiceClient(m_callbackInstance, "NetTcpBinding_IHelloIndigoService");
            }
            else if (this.rbNamedPipesBinding.Checked)
            {
                m_proxy = new localhost.HelloIndigoServiceClient(m_callbackInstance, "NetNamedPipeBinding_IHelloIndigoService");
            }
            else if (this.rbHttpBinding.Checked)
            {
                m_proxy = new localhost.HelloIndigoServiceClient(m_callbackInstance, "WSDualHttpBinding_IHelloIndigoService");

                WSDualHttpBinding binding = m_proxy.Endpoint.Binding as WSDualHttpBinding;
                binding.ClientBaseAddress = new Uri("http://localhost:8100");
            }
            else
            {
                m_proxy = new localhost.HelloIndigoServiceClient(m_callbackInstance, "CustomBinding_IHelloIndigoService");

                WSDualHttpBinding binding = m_proxy.Endpoint.Binding as WSDualHttpBinding;
                binding.ClientBaseAddress = new Uri("http://localhost:8100");
            }
        }
Beispiel #9
0
        public MainWindow(Room user)
        {
            InitializeComponent();
            this.user          = user;
            User_label.Content = "User: "******"http://localhost:8000/ChatProgram/ChatService/ChatHost");

            binding.ClientBaseAddress = new Uri("http://localhost:8000/myChatClient/");

            // Create Room instance to store client userName and Message
            this.localClient          = new Room();
            this.localClient.UserName = user.UserName;
            this.localClient.Message  = ChatTextBlock.Text;

            // Adding client to OnlineClients list
            OnlineClients.Add(localClient.UserName, user);

            //Construct InstanceContext to handle messages on callback interface.
            InstanceContext context = new InstanceContext(this);

            proxy = new ChatServiceClient(context);

            //Show client joined on UI
            proxy.SendMessageAsync(localClient);
            // Show timestamp on UI
            ChatTextBlock.Text = "Connected at: " + DateTime.Now;
            // To add a new line
            ChatTextBlock.Inlines.Add(new LineBreak());
            //proxy.Open();
        }
Beispiel #10
0
        static void Main(string[] args)
        {
            Uri         baseAddress = new Uri("http://localhost:8001/LamaczHasel/");
            ServiceHost selfHost    = new ServiceHost(typeof(LHService), new Uri[] { baseAddress });

            try
            {
                WSDualHttpBinding binding = new WSDualHttpBinding();
                binding.MaxBufferPoolSize      = 2147483647;
                binding.MaxReceivedMessageSize = 2147483647;
                binding.OpenTimeout            = new TimeSpan(0, 0, 10);
                binding.CloseTimeout           = new TimeSpan(0, 0, 10);
                binding.SendTimeout            = new TimeSpan(0, 0, 10);
                binding.ReceiveTimeout         = new TimeSpan(0, 10, 0);


                selfHost.AddServiceEndpoint(typeof(ILHService), binding, "LHService");
                ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
                smb.HttpGetEnabled = true;
                selfHost.Description.Behaviors.Find <ServiceDebugBehavior>().IncludeExceptionDetailInFaults = true;
                selfHost.Description.Behaviors.Add(smb);
                selfHost.Open();
                Console.WriteLine("Serwis działa....");
                Console.WriteLine("Nacisnij <ENTER> by zakonczyc.");
                Console.WriteLine();
                Console.ReadLine();
                selfHost.Close();
            }
            catch (CommunicationException ce)
            {
                Console.WriteLine("Przechwyciłem wyjatek: {0}", ce.Message);
                Console.ReadLine();
                selfHost.Abort();
            }
        }
Beispiel #11
0
        static void Main(string[] args)
        {
            Console.WriteLine("Please connect to service.");
            string       cmd       = Console.ReadLine();
            bool         connected = false;
            IFileService client    = null;

            while (!connected && !cmd.ToLower().Equals("quit"))
            {
                string command = cmd.Split(' ')[0];
                if (command.ToLower().Equals("connect") && cmd.Split(' ').Count() > 2)
                {
                    string          serviceHost    = cmd.Split(' ')[1];
                    var             binding        = new WSDualHttpBinding();
                    var             address        = new EndpointAddress($"http://{serviceHost}/FileService.svc");
                    NotifyCallback  notifyCallback = new NotifyCallback();
                    InstanceContext instance       = new InstanceContext(notifyCallback);
                    var             factory        = new DuplexChannelFactory <IFileService>(notifyCallback, binding, address);
                    client = factory.CreateChannel();
                    String answer = client.RunCommand(cmd);
                    if (answer.ToLower().Contains("error"))
                    {
                        Console.WriteLine(answer);
                        cmd = Console.ReadLine();
                    }
                    else
                    {
                        ClientSession.User = answer;
                        connected          = true;
                    }
                }
                else
                {
                    Console.WriteLine("You are not connected! Please connect!");
                    cmd = Console.ReadLine();
                }
            }
            if (cmd.ToLower() != "quit")
            {
                Console.WriteLine("Welcome! You are connected!");
                Console.WriteLine(client.CurrentPath());
                cmd = Console.ReadLine();
                while (!cmd.ToLower().Equals("quit"))
                {
                    if (client != null)
                    {
                        String answer = client.RunCommand(cmd);
                        Console.WriteLine(answer);
                        Console.WriteLine(client.CurrentPath());
                    }
                    cmd = Console.ReadLine();
                }
                if (client != null)
                {
                    client.Logout();
                }
            }
            Console.WriteLine("Press enter to exit");
            Console.ReadLine();
        }
Beispiel #12
0
        static void Main(string[] args)
        {
            using (ServiceHost host = new ServiceHost(typeof(ChatManagerService),
                                                      new Uri("http://localhost:8080/chatmgr")))
            {
                ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
                smb.HttpGetEnabled = true;
                //smb.HttpGetBinding = new WebHttpBinding();
                smb.HttpGetUrl = new Uri(host.BaseAddresses[0] + "/mex");

                ProfanityInterceptorBehavior pib = new ProfanityInterceptorBehavior();

                host.Description.Behaviors.Add(smb);
                //host.Description.Behaviors.Add(pib);

                //Manually create the service endpoint, and add to host collection
                Binding             binding     = new WSDualHttpBinding();
                EndpointAddress     address     = new EndpointAddress(host.BaseAddresses[0] + "/duplex");
                ContractDescription description = ContractDescription.GetContract(typeof(IChatManager));
                ServiceEndpoint     endpoint    = new ServiceEndpoint(description, binding, address);
                endpoint.EndpointBehaviors.Add(pib);
                host.AddServiceEndpoint(endpoint);

                //Add the metadata endpoint directly
                host.AddServiceEndpoint(typeof(IMetadataExchange),
                                        MetadataExchangeBindings.CreateMexHttpBinding(),
                                        "mex");

                host.Open();
                PrintServiceDescription(host);
                Console.ReadKey();
            }
        }
Beispiel #13
0
        static void Main(string[] args)
        {
            string url = "http://localhost:8080/ChatService";

            WSDualHttpBinding binding  = new WSDualHttpBinding();
            EndpointAddress   endpoint = new EndpointAddress(url);

            InstanceContext context = new InstanceContext(new ConsoleCallback());

            DuplexChannelFactory <IChatService> channelFactory = new DuplexChannelFactory <IChatService>(context, binding, endpoint);

            IChatService client = channelFactory.CreateChannel();

            Console.Write("Enter username: "******"Enter message or (q)uit: ");
            string message = Console.ReadLine();

            while (message != "q")
            {
                client.Send(message);
                message = Console.ReadLine();
            }
        }
Beispiel #14
0
        public static IGinService CreateServiceClient(object context, int port)
        {
            var iContext  = new InstanceContext(context);
            var myBinding = new WSDualHttpBinding
            {
                ClientBaseAddress      = new Uri(@"http://localhost:8738/GinService/ShellExtension/" + Environment.UserName + "/" + port),
                MaxBufferPoolSize      = int.MaxValue,
                MaxReceivedMessageSize = int.MaxValue,
                OpenTimeout            = TimeSpan.FromMinutes(1.0),
                CloseTimeout           = TimeSpan.FromMinutes(1.0),
                SendTimeout            = TimeSpan.FromSeconds(1),
                ReceiveTimeout         = TimeSpan.FromSeconds(1),
                ReaderQuotas           = new XmlDictionaryReaderQuotas
                {
                    MaxArrayLength         = int.MaxValue,
                    MaxBytesPerRead        = int.MaxValue,
                    MaxDepth               = int.MaxValue,
                    MaxNameTableCharCount  = int.MaxValue,
                    MaxStringContentLength = int.MaxValue
                }
            };
            var endpointIdentity = EndpointIdentity.CreateDnsIdentity("localhost");
            var myEndpoint       = new EndpointAddress(new Uri("http://localhost:8733/GinService/"), endpointIdentity);

            var myChannelFactory = new ChannelFactory <IGinService>(myBinding, myEndpoint);

            var client = myChannelFactory.CreateChannel();

            return(client);
        }
Beispiel #15
0
        /// <summary>
        /// Creates a subscription for the message.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="message"></param>
        /// <returns></returns>
        public Subscription CreateSubscription <T>(T message) where T : Message
        {
            Subscription sub = new Subscription();

            sub.SubscriptionID = new Guid();
            sub.Message        = message;

            if (m_ChannelFactory != null && m_ChannelFactory.Endpoint.Binding is WSDualHttpBinding)
            {
                WSDualHttpBinding dhb = (WSDualHttpBinding)m_ChannelFactory.Endpoint.Binding;
                if (dhb.ClientBaseAddress != null)
                {
                    sub.Address = dhb.ClientBaseAddress.ToString();
                }

                if (dhb.ReliableSession.InactivityTimeout < TimeSpan.FromMinutes(30))
                {
                    dhb.ReliableSession.InactivityTimeout = TimeSpan.FromMinutes(30);
                }
            }
            else if (m_ChannelFactory != null && m_ChannelFactory.Endpoint.Binding is NetTcpBinding)
            {
                NetTcpBinding ntb = (NetTcpBinding)m_ChannelFactory.Endpoint.Binding;

                if (ntb.ReliableSession.InactivityTimeout < TimeSpan.FromMinutes(30))
                {
                    ntb.ReliableSession.InactivityTimeout = TimeSpan.FromMinutes(30);
                }
            }

            sub.SubscriptionID = Guid.NewGuid();
            m_Subscription     = sub;

            return(sub);
        }
Beispiel #16
0
        static void Main(string[] args)
        {
            Uri               baseAddress2 = new Uri(UriString2);
            ServiceHost       myHost2      = new ServiceHost(typeof(myCallbackCalculator), baseAddress2);
            WSDualHttpBinding myBanding2   = new WSDualHttpBinding();

            try
            {
                ServiceEndpoint         endpoint2 = myHost2.AddServiceEndpoint(typeof(ICallbackBank), myBanding2, "CallbackKalkulator");
                ServiceMetadataBehavior smb2      = new ServiceMetadataBehavior();
                smb2.HttpGetEnabled = true;
                myHost2.Description.Behaviors.Add(smb2);
                myHost2.Open();
                Console.WriteLine("--->CallbackKalkulator  is  running.");
                Console.WriteLine("--->Calculator is running.");
                Console.WriteLine("--->Press <Enter> to stop.\n");
                Console.ReadLine();
                myHost2.Close();
                Console.WriteLine("--->Service finished to work.");
            }
            catch (CommunicationException ce)
            {
                Console.WriteLine("Exception Occured: {0}", ce.Message);
                myHost2.Abort();
            }
        }
Beispiel #17
0
        static void Main(string[] args)
        {
            Console.WriteLine("Client running on thread {0}", Thread.CurrentThread.GetHashCode());
            Console.WriteLine();

            Program         p       = new Program();
            InstanceContext context = new InstanceContext(p);

            using (localhost.HelloIndigoServiceClient proxy = new HelloIndigoServiceClient(context))
            {
                WSDualHttpBinding b = proxy.Endpoint.Binding as WSDualHttpBinding;
                if (b != null)
                {
                    b.ClientBaseAddress = new Uri("http://localhost:8100");
                }


                Console.WriteLine("Calling HelloIndigo() - one-way");
                proxy.HelloIndigo("Hello from client.");
                Console.WriteLine("Returned from HelloIndigo()");

                Console.WriteLine("Client SessionId = {0}", proxy.InnerChannel.SessionId);

                Console.WriteLine("Calling HelloIndigo2() - not one-way");
                proxy.HelloIndigo2("Hello from client.");
                Console.WriteLine("Returned from HelloIndigo2()");

                Console.ReadLine();
            }
            Console.ReadLine();
        }
Beispiel #18
0
        static void Main(string[] args)
        {
            Console.WriteLine("Hi from Suscriber Console!");
            InstanceContext site = new InstanceContext(null, new Program());

            NotificationServiceClient client = new NotificationServiceClient(site);

            //create a unique callback address so multiple clients can run on one machine
            WSDualHttpBinding binding = (WSDualHttpBinding)client.Endpoint.Binding;
            string            clientcallbackaddress = binding.ClientBaseAddress.AbsoluteUri;

            clientcallbackaddress    += Guid.NewGuid().ToString();
            binding.ClientBaseAddress = new Uri(clientcallbackaddress);

            //Subscribe.
            Console.WriteLine("Subscribing");
            client.Subscribe();

            Console.WriteLine();
            Console.WriteLine("Press ENTER to unsubscribe and shut down client");
            Console.ReadLine();

            Console.WriteLine("Unsubscribing");
            client.Unsubscribe();

            //Closing the client gracefully closes the connection and cleans up resources
            client.Close();
        }
Beispiel #19
0
        public bool Subscribe(string name)
        {
            if (producers.ContainsKey(name))
            {
                return(false);
            }

            var binding = new WSDualHttpBinding();

            binding.SendTimeout = TimeSpan.FromSeconds(10.0);
            var client = new BondDataService.ProducerClient(context, binding, new EndpointAddress(uri));

            if (!producers.TryAdd(name, client))
            {
                return(false);
            }
            try
            {
                producers[name].Subscribe(name);
            }
            catch
            {
                return(false);
            }

            return(true);
        }
        protected internal override void InitializeFrom(Binding binding)
        {
            base.InitializeFrom(binding);
            WSDualHttpBinding binding2 = (WSDualHttpBinding)binding;

            this.BypassProxyOnLocal = binding2.BypassProxyOnLocal;
            if (binding2.ClientBaseAddress != null)
            {
                this.ClientBaseAddress = binding2.ClientBaseAddress;
            }
            this.TransactionFlow        = binding2.TransactionFlow;
            this.HostNameComparisonMode = binding2.HostNameComparisonMode;
            this.MaxBufferPoolSize      = binding2.MaxBufferPoolSize;
            this.MaxReceivedMessageSize = binding2.MaxReceivedMessageSize;
            this.MessageEncoding        = binding2.MessageEncoding;
            if (binding2.ProxyAddress != null)
            {
                this.ProxyAddress = binding2.ProxyAddress;
            }
            this.ReliableSession.InitializeFrom(binding2.ReliableSession);
            this.TextEncoding       = binding2.TextEncoding;
            this.UseDefaultWebProxy = binding2.UseDefaultWebProxy;
            this.Security.InitializeFrom(binding2.Security);
            this.ReaderQuotas.InitializeFrom(binding2.ReaderQuotas);
        }
Beispiel #21
0
        public static void SetClientBaseAddress <T>(this DuplexClientBase <T> proxy, int port, string machineIpOrName) where T : class
        {
            WSDualHttpBinding binding = proxy.Endpoint.Binding as WSDualHttpBinding;

            Debug.Assert(binding != null);
            binding.ClientBaseAddress = new Uri("http://" + machineIpOrName + ":" + port + "/");
        }
Beispiel #22
0
        static void Main(string[] args)
        {
            WSDualHttpBinding binding = new WSDualHttpBinding();

            //  EndpointAddress baseAddress2 = new EndpointAddress("http://localhost:64080/crm");
            binding.ClientBaseAddress = new Uri("http://localhost:64080/client");
            binding.Security.Mode     = WSDualHttpSecurityMode.None;


            Uri baseAddress = new Uri("http://localhost:64080/crm");

            using (ServiceHost host = new ServiceHost(typeof(CrmRepositoryService), baseAddress))
            {
                host.AddServiceEndpoint(typeof(ICRMRepository), binding, baseAddress);

                ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
                smb.HttpGetEnabled = true;
                smb.MetadataExporter.PolicyVersion = PolicyVersion.Policy15;

                host.Description.Behaviors.Add(smb);
                ServiceAuthenticationBehavior bechAuthenticationBehavior = new ServiceAuthenticationBehavior();
                bechAuthenticationBehavior.AuthenticationSchemes = AuthenticationSchemes.None;


                host.Open();

                Console.WriteLine($"The service is ready at {baseAddress}");
                Console.WriteLine("Press <Enter> to stop the service.");
                Console.ReadLine();

                // Close the ServiceHost.
                host.Close();
            }
        }
Beispiel #23
0
        private void BtStartServiceClick(object sender, EventArgs e)
        {
            if (ServiceStarted)
            {
                host.Close();
                ServiceStarted = false;
            }
            else
            {
                baseAddress = new Uri(txbaseaddress.Text);
                host        = new ServiceHost(instanceType, baseAddress);
                ServiceMetadataBehavior behavior = new ServiceMetadataBehavior();
                behavior.HttpGetEnabled = true;
                host.Description.Behaviors.Add(behavior);
                WSDualHttpBinding ws = new WSDualHttpBinding();
                ws.MaxBufferPoolSize                   = int.MaxValue;
                ws.MaxReceivedMessageSize              = int.MaxValue;
                ws.ReaderQuotas.MaxArrayLength         = int.MaxValue;
                ws.ReaderQuotas.MaxBytesPerRead        = int.MaxValue;
                ws.ReaderQuotas.MaxStringContentLength = int.MaxValue;

                host.AddServiceEndpoint(contractType, ws, "");
                //host.AddServiceEndpoint(contractType, new NetMsmqBinding(), "");

                if (cbMex.Checked)
                {
                    host.AddServiceEndpoint(typeof(IMetadataExchange), ws, "MEX");
                }
                host.Open();
                lbmessage.Visible = true;
                lbmessage.Text    = "Host Option is running...";
                //MessageBox.Show(" " + svcEndpoint.Address);
                ServiceStarted = true;
            }
        }
        internal static void DemandClientConnectionPermissions(ServiceEndpoint endpoint)
        {
            PermissionSet connectionSet = new PermissionSet(PermissionState.None);

            if (endpoint.Binding is NetTcpBinding)
            {
                connectionSet.AddPermission(new SocketPermission(NetworkAccess.Connect, TransportType.Tcp, endpoint.Address.Uri.Host, endpoint.Address.Uri.Port));
                connectionSet.AddPermission(new DnsPermission(PermissionState.Unrestricted));
            }
            if (endpoint.Binding is WebHttpBinding || endpoint.Binding is WSHttpBinding || endpoint.Binding is BasicHttpBinding || endpoint.Binding is WSDualHttpBinding)
            {
                connectionSet.AddPermission(new WebPermission(NetworkAccess.Connect, endpoint.Address.Uri.AbsoluteUri));
            }
            //On the client, demand hosting permission for duplex over HTTP
            if (endpoint.Binding is WSDualHttpBinding)
            {
                connectionSet.AddPermission(new AspNetHostingPermission(AspNetHostingPermissionLevel.Minimal));

                WSDualHttpBinding binding = endpoint.Binding as WSDualHttpBinding;

                Uri callbackUri = binding.ClientBaseAddress ?? new Uri("http://localhost:80/");

                connectionSet.AddPermission(new WebPermission(NetworkAccess.Accept, callbackUri.AbsoluteUri));
            }
            if (endpoint.Binding is NetMsmqBinding)
            {
                string path = QueuedServiceHelper.GetQueueFromUri(endpoint.Address.Uri);
                connectionSet.AddPermission(new MessageQueuePermission(MessageQueuePermissionAccess.Send, path));
            }
            connectionSet.Demand();
        }
        protected override ContextMenuStrip CreateMenu()
        {
            var menu = new ContextMenuStrip();

            var baseItem = new ToolStripMenuItem("Gin Repository");

            var iContext         = new InstanceContext(this);
            var myBinding        = new WSDualHttpBinding();
            var myEndpoint       = new EndpointAddress("http://localhost:8733/Design_Time_Addresses/GinService/");
            var myChannelFactory = new DuplexChannelFactory <IGinService>(iContext, myBinding, myEndpoint);

            var client = myChannelFactory.CreateChannel();

            try
            {
                baseItem.DropDownItems.AddRange(client.IsBasePath(SelectedItemPaths.First())
                    ? GetBaseDirectoryMenu()
                    : GetFileMenu());

                ((ICommunicationObject)client).Close();
            }
            catch
            {
                ((ICommunicationObject)client).Abort();
            }
            return(menu);
        }
 static bool MessageSecurityEnabled(ServiceEndpoint endpoint)
 {
     if (endpoint.Binding is NetTcpBinding)
     {
         NetTcpBinding binding = endpoint.Binding as NetTcpBinding;
         return(binding.Security.Mode == SecurityMode.Message);
     }
     if (endpoint.Binding is NetNamedPipeBinding)
     {
         return(false);
     }
     if (endpoint.Binding is NetMsmqBinding)
     {
         NetMsmqBinding binding = endpoint.Binding as NetMsmqBinding;
         return(binding.Security.Mode == NetMsmqSecurityMode.Message);
     }
     if (endpoint.Binding is WSHttpBinding)
     {
         WSHttpBinding binding = endpoint.Binding as WSHttpBinding;
         return(binding.Security.Mode == SecurityMode.Message);
     }
     if (endpoint.Binding is WSDualHttpBinding)
     {
         WSDualHttpBinding binding = endpoint.Binding as WSDualHttpBinding;
         return(binding.Security.Mode == WSDualHttpSecurityMode.Message);
     }
     if (endpoint.Binding is BasicHttpBinding)
     {
         BasicHttpBinding binding = endpoint.Binding as BasicHttpBinding;
         return(binding.Security.Mode == BasicHttpSecurityMode.Message);
     }
     return(false);
 }
        public void Start()
        {
            try
            {
                this.m_Host = new ServiceHost(typeof(MasterService), new Uri(Constants.TEST_AUTOMATION_SERIVICE_ENDPOINT));

                WSDualHttpBinding binding = new WSDualHttpBinding();
                binding.OpenTimeout    = TimeSpan.MaxValue;
                binding.CloseTimeout   = TimeSpan.MaxValue;
                binding.SendTimeout    = TimeSpan.MaxValue;
                binding.ReceiveTimeout = TimeSpan.MaxValue;

                this.m_Host.AddServiceEndpoint(typeof(IAutomationIDGeneratorServiceContract), binding, "");

                ServiceMetadataBehavior serviceBehavior = new ServiceMetadataBehavior();
                serviceBehavior.HttpGetEnabled = true;
                this.m_Host.Description.Behaviors.Add(serviceBehavior);

                this.m_Host.Open();
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.Message);
                this.m_Host?.Abort();
            }
            finally
            {
            }
        }
        public MainWindow()
        {
            InitializeComponent();
            userNameTb.Text = $"Fred {Guid.NewGuid().ToString().Substring(0, 4)}";

            if (!!!!true)
            {
                var tcp = new NetTcpBinding();
                tcp.Security.Mode = SecurityMode.TransportWithMessageCredential;
                tcp.Security.Transport.ClientCredentialType = TcpClientCredentialType.Certificate;

                tcp.MaxReceivedMessageSize = int.MaxValue;
                EndpointIdentity identity = EndpointIdentity.CreateDnsIdentity("MyROOTCert");
                EndpointAddress  address  = new EndpointAddress(new Uri("net.tcp://localhost:1"), identity);


                cf = new DuplexChannelFactory <IServer>(this, tcp, address);
                cf.Credentials.ClientCertificate.SetCertificate(StoreLocation.CurrentUser, StoreName.Root,
                                                                X509FindType.FindByThumbprint, "14295bd222c188a881dbe88585333dd564a5b57a");
                cf.Credentials.ServiceCertificate.Authentication.CertificateValidationMode = System.ServiceModel.Security.X509CertificateValidationMode.None;
            }
            else
            {
                var wsDual = new WSDualHttpBinding();
                wsDual.Security.Mode = WSDualHttpSecurityMode.Message;
                cf = new DuplexChannelFactory <IServer>(this, wsDual, new EndpointAddress("http://localhost:2"));
            }

            SetUi(false);
        }
Beispiel #29
0
        protected override void OnStart(string[] args)
        {
            if (serviceHost != null)
            {
                serviceHost.Close();
            }

            Uri subscriptionAddress = new Uri("http://localhost:9000/PubSubMonitoringService/");
            Uri publishingAddress   = new Uri("net.tcp://localhost:9001/PubSubMonitoringService/");

            serviceHost = new ServiceHost(typeof(MonitoringService));
            // Binding for handling subscriptions the subscriptions.
            WSDualHttpBinding subscriptionBinding = new WSDualHttpBinding();

            serviceHost.AddServiceEndpoint(typeof(IPubSubMonitoringService), subscriptionBinding, subscriptionAddress);

            // Binding for handling monitoring messages. We use NetTcpBinding here because it's way faster.
            NetTcpBinding publishBinding = new NetTcpBinding(SecurityMode.None, false);

            serviceHost.AddServiceEndpoint(typeof(IPubSubMonitoringService), publishBinding, publishingAddress);

            ServiceMetadataBehavior smb = new ServiceMetadataBehavior();

            smb.HttpGetEnabled = true;
            smb.HttpGetUrl     = subscriptionAddress;
            serviceHost.Description.Behaviors.Add(smb);
            serviceHost.Open();
        }
Beispiel #30
0
        public SQLWebServiceModel(MessageCredentialType MessageCredentialType, string ServiceURL)
        {
            this.ServiceURL = ServiceURL;

            WSDualHttpBinding binding = new WSDualHttpBinding(WSDualHttpSecurityMode.Message);
            //끝점
            EndpointAddress EndpointURL = new EndpointAddress
                                          (
                new Uri(this.ServiceURL)
                                          );

            //보안설정
            binding.Security.Message.ClientCredentialType = MessageCredentialType;
            WebServiceChannel = new ChannelFactory <IWebService>
                                (
                new ServiceEndpoint
                (
                    ContractDescription.GetContract(typeof(IWebService)),
                    binding,
                    EndpointURL
                )
                                );
            //인증서 유효성 검사 안하게 한다
            WebServiceChannel.Credentials.ServiceCertificate.Authentication.CertificateValidationMode =
                X509CertificateValidationMode.None;
        }