Example #1
0
        public void SingletonSessionsTests()
        {
            Binding binding = new WSHttpBinding();
            string address = "http://localhost/" + Guid.NewGuid().ToString();
            using (ServiceHost host =
                      new ServiceHost(typeof(SingletonCounter), new Uri(address)))
            {
                host.AddServiceEndpoint(typeof(ISessionRequired), binding, "withSession");
                host.AddServiceEndpoint(typeof(ISessionNotAllowed), binding, "woutSession");

                host.Open();

                ISessionRequired withSession =
                    ChannelFactory<ISessionRequired>.CreateChannel(
                        binding,
                        new EndpointAddress(address + "/withSession"));
                withSession.IncrementCounter();
                ((ICommunicationObject)withSession).Close();

                ISessionNotAllowed woutSession =
                    ChannelFactory<ISessionNotAllowed>.CreateChannel(
                        binding,
                        new EndpointAddress(address + "/woutSession"));
                woutSession.IncrementCounter();
                ((ICommunicationObject)woutSession).Close();

            }
        }
Example #2
0
 public static void MyClassInitialize(TestContext testContext)
 {
     binding = new NetNamedPipeBinding();
     host = new ServiceHost(typeof(MyService));
     host.AddServiceEndpoint(typeof(IChangeResource), binding, address);
     host.Open();
 }
        public void CallbackToSyncContext()
        {
            var path = @"net.pipe://127.0.0.1/" + this.GetType().Name + MethodBase.GetCurrentMethod().Name;
            var binding = new NetNamedPipeBinding() { MaxConnections = 5 };

            using (var server = new ServiceHost(new SyncCallbackService(), new Uri(path)))
            {

                server.AddServiceEndpoint(typeof(ISyncCallbackService), binding, path);

                server.Open();
                using (var syncContext = new StaSynchronizationContext())
                {
                    InstanceContext context = null;
                    NDceRpc.ServiceModel.DuplexChannelFactory<ISyncCallbackService> channelFactory = null;
                    ISyncCallbackService client = null;
                    syncContext.Send(_ => SynchronizationContext.SetSynchronizationContext(syncContext), null);
                    syncContext.Send(_ => context = new InstanceContext(new SyncCallbackServiceCallback()), null);
                    syncContext.Send(_ => channelFactory = new NDceRpc.ServiceModel.DuplexChannelFactory<ISyncCallbackService>(context, binding),null);
                    syncContext.Send(_ => client =  channelFactory.CreateChannel(new EndpointAddress(path)),null);
                    using (channelFactory)
                    {
                        var callbackThread = client.Call();
                        Assert.AreEqual(syncContext.ManagedThreadId, callbackThread);
                    }
                }

            }
        }
        public void ServerAncClientExceptionsEndpointBehavior()
        {
            var hook = new ExceptionsEndpointBehaviour();
            var address = @"net.pipe://127.0.0.1/test" + this.GetType().Name + "_" + MethodBase.GetCurrentMethod().Name;
            var serv = new ExceptionService();
            using (var host = new ServiceHost(serv, new Uri[] { new Uri(address), }))
            {
                var b = new NetNamedPipeBinding();
                var serverEndpoint = host.AddServiceEndpoint(typeof(IExceptionService), b, address);
                serverEndpoint.Behaviors.Add(hook);

                host.Open();

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

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

                try
                {
                    c.DoException("message");
                }
                catch (InvalidOperationException ex)
                {
                    StringAssert.AreEqualIgnoringCase("message", ex.Message);
                }
                host.Abort();
            }
        }
Example #5
0
        public void CallServiceReturningSession2Times_sessionAreEqual()
        {
            var address = @"net.pipe://127.0.0.1/1/test.test/test" + MethodBase.GetCurrentMethod().Name;
            var binding = new NetNamedPipeBinding();

            var data = new CallbackData { Data = "1" };
            var srv = new CallbackService(data);
            var callback = new CallbackServiceCallback();

            using (var host = new ServiceHost(srv, new Uri(address)))
            {
                host.AddServiceEndpoint(typeof(ICallbackService), binding, address);
                host.Open();

                using (var factory = new DuplexChannelFactory<ICallbackService>(new InstanceContext(callback), binding))
                {
                    var client = factory.CreateChannel(new EndpointAddress(address));
                    client.Call();
                }

                callback.Wait.WaitOne();

                Assert.AreEqual(data.Data, callback.Called.Data);
            }
        }
Example #6
0
        public void Ipc_byteArray()
        {
            var uri = "ipc:///" + MethodBase.GetCurrentMethod().Name;
            using (var server = new ServiceHost(new Service(), new Uri(uri)))
            {
                var binding = new LocalBinding { MaxConnections = 5 };
                server.AddServiceEndpoint(typeof(IService), binding, uri);
                server.Open();
                Thread.Sleep(100);
                using (var channelFactory = new ChannelFactory<IService>(binding))
                {

                    var client = channelFactory.CreateChannel(new EndpointAddress(uri));
                    client.Execute(new byte[0]);

                    byte[] bytes = new byte[512];
                    new Random().NextBytes(bytes);

                    var timer = new Stopwatch();
                    timer.Start();

                    for (int i = 0; i < 5000; i++)
                        client.Execute(bytes);

                    timer.Stop();
                    Trace.WriteLine(timer.ElapsedMilliseconds.ToString() + " ms", MethodBase.GetCurrentMethod().Name);
                }
            }
        }
Example #7
0
        public void CallAsync_wait_done()
        {
            var address = @"net.pipe://127.0.0.1/" + this.GetType().Name + "_" + MethodBase.GetCurrentMethod().Name;
            var binding = new NetNamedPipeBinding();

            var done = new ManualResetEvent(false);
            var srv = new AsyncService(done);
            var callback = new AsyncServiceCallback();

            using (var host = new ServiceHost(srv, new Uri(address)))
            {
                host.AddServiceEndpoint(typeof(IAsyncService), binding, address);
                host.Open();

                ThreadPool.QueueUserWorkItem(_ =>
                {
                    using (var factory = new DuplexChannelFactory<IAsyncService>(new InstanceContext(callback), binding))
                    {
                        var client = factory.CreateChannel(new EndpointAddress(address));
                        AsyncCallback act = (x) =>
                        {
                            Assert.AreEqual(x.AsyncState, 1);
                        };
                        var result = client.BeginServiceAsyncMethod(act, 1);
                        result.AsyncWaitHandle.WaitOne();
                        Assert.AreEqual(result.AsyncState, 1);
                        client.EndServiceAsyncMethod(result);

                    }
                });

                done.WaitOne();
            }
        }
        public void CallServiceReturningSession2TimesFor2Channels_sessionAreDifferentForDifferentChannels()
        {
            var address = @"net.pipe://127.0.0.1/1/test.test/test" + MethodBase.GetCurrentMethod().Name;

            var serv = new SessionService();
            var host = new ServiceHost(serv, new Uri(address));
            var b = new NetNamedPipeBinding();
            host.AddServiceEndpoint(typeof(ISessionService), b, address);
            var f1 = new ChannelFactory<ISessionService>(b);
            var f2 = new ChannelFactory<ISessionService>(b);
            var client1 = f1.CreateChannel(new EndpointAddress(address));
            var client2 = f2.CreateChannel(new EndpointAddress(address));
            host.Open();

            var session11 = client1.Call();
            var session21 = client2.Call();
            var session22 = client2.Call();
            var session12 = client1.Call();

            f1.Dispose();
            f2.Dispose();
            host.Dispose();
            Assert.AreEqual(session11, session12);
            Assert.AreEqual(session21, session22);
            Assert.AreNotEqual(session11, session21);
        }
Example #9
0
        public void TestOneWayCallbackConcurencyOnNamedPipe()
        {
            var address = @"net.pipe://127.0.0.1/testpipename" + MethodBase.GetCurrentMethod().Name;
            var srv = new CallbackService();
            var callback = new CallbackServiceCallback();
            using (var server = new ServiceHost(srv, new Uri(address)))
            {
                server.AddServiceEndpoint(typeof(ICallbackService), new NetNamedPipeBinding { }, address);
                server.Open();

                using (var channelFactory = new DuplexChannelFactory<ICallbackService>(new InstanceContext(callback), new NetNamedPipeBinding { }))
                {

                    var client = channelFactory.CreateChannel(new EndpointAddress(address));

                    for (int i = 0; i < 20; i++)
                        client.OneWayExecute();
                    while (callback.Count != 20)
                    {
                        Thread.Sleep(10);
                    }

                }
            }
        }
 public void FlowRequiredButNotSupported()
 {
     ServiceHost host = new ServiceHost(typeof(TestService2));
     BasicHttpBinding binding = new BasicHttpBinding();  // Does not support transactions
     string address = "http://localhost:8080/" + Guid.NewGuid().ToString();
     host.AddServiceEndpoint(typeof(ITestContract2), binding, address);
     host.Open();
 }
 public void FlowRequiredButNotEnabled()
 {
     ServiceHost<TestService2> host = new ServiceHost<TestService2>();
     NetNamedPipeBinding binding = new NetNamedPipeBinding();
     binding.TransactionFlow = false;  // default
     string address = "net.pipe://localhost/" + Guid.NewGuid().ToString();
     host.AddServiceEndpoint(typeof(ITestContract2), binding, address);
     host.Open();
 }
Example #12
0
        public void Open_2Endpoints_callsBoth()
        {
            var baseAddress = @"net.pipe://127.0.0.1/" + this.GetType().Name + MethodBase.GetCurrentMethod().Name;
            var serv = new Service(null);
            using (var host = new ServiceHost(serv, new Uri[] { new Uri(baseAddress) }))
            {
                var binding = new NetNamedPipeBinding();
                host.AddServiceEndpoint(typeof(IService), binding, baseAddress + "/1");
                host.AddServiceEndpoint(typeof(IService), binding, baseAddress + "/2");
                host.Open();
                using (var channelFatory = new ChannelFactory<IService>(binding))
                {
                    var c1 = channelFatory.CreateChannel(new EndpointAddress(baseAddress + "/1"));
                    var c2 = channelFatory.CreateChannel(new EndpointAddress(baseAddress + "/2"));
                    c1.DoWithParamsAndResult("", Guid.Empty);
                    c2.DoWithParamsAndResult("", Guid.Empty);
                }

            }
        }
 public void FlowRequiredAndEnabled()
 {
     using (ServiceHost<TestService2> host = new ServiceHost<TestService2>())
     {
         NetNamedPipeBinding binding = new NetNamedPipeBinding();
         binding.TransactionFlow = true;
         string address = "net.pipe://localhost/" + Guid.NewGuid().ToString();
         host.AddServiceEndpoint<ITestContract2>(binding, address);
         host.Open();
     }
 }
 public void EnableMetadataExchange_MultipleBaseAddresses()
 {
     ServiceHost<TestService> host;
     using (host = new ServiceHost<TestService>("http://localhost:8080", "net.tcp://localhost:8081"))
     {
         host.AddServiceEndpoint(typeof(ITestContract), new WSHttpBinding(), "Test");
         Assert.IsFalse(host.MetadataExchangeEnabled);
         host.EnableMetadataExchange();
         Assert.AreEqual(2, host.Description.Endpoints.Count<ServiceEndpoint>(ep =>
             ep.Contract.ContractType == typeof(IMetadataExchange)));
     }
 }
 public void PerSessionTransactionService()
 {
     var address = "net.pipe://localhost/" + Guid.NewGuid();
     using (var host = new ServiceHost(typeof(PerSessionService)))
     using (var proxy = new ServiceClient(binding, address))
     {
         host.AddServiceEndpoint(typeof(IInstanceIdGetter), binding, address);
         host.Open();
         var first = proxy.GetInstanceId();
         var second = proxy.GetInstanceId();
         Assert.AreEqual(second, first);
     }
 }
Example #16
0
        public void InvokenBlockingWithParams_resultObtained()
        {
            var address = @"net.pipe://127.0.0.1/1/test.test/test";

            var serv = new Service(null);
            var host = new ServiceHost(serv, new Uri(address));
            var b = new NetNamedPipeBinding();
            host.AddServiceEndpoint(typeof(IService), b, address);
            host.Open();
            var f = new ChannelFactory<IService>(b);
            var c = f.CreateChannel(new EndpointAddress(address));
            var result = c.DoWithParamsAndResult(":)", Guid.NewGuid());
            Assert.AreEqual(2, result.d1);
            host.Dispose();
        }
Example #17
0
        public void InterfaceInheritance()
        {
            var address = @"ipc:///test" + MethodBase.GetCurrentMethod().Name;
            var serv = new InheritanceService();
            var host = new ServiceHost(serv, new Uri(address));
            var b = new LocalBinding();
            host.AddServiceEndpoint(typeof(IInheritanceService), b, address);
            host.Open();
            var f = new ChannelFactory<IInheritanceService>(b);
            var c = f.CreateChannel(new EndpointAddress(address));
            c.Do();
            c.DoBase();

            host.Dispose();
        }
Example #18
0
        public void DisposedChannelFactory_call()
        {
            var address = @"net.pipe://127.0.0.1/" + Guid.NewGuid().ToString("N");
            var serv = new SimpleService();
            var b = new NetNamedPipeBinding();

            using (var host = new ServiceHost(serv, new Uri[] { new Uri(address), }))
            {
                host.AddServiceEndpoint(typeof(ISimpleService), b, address);
                host.Open();
                var f = new ChannelFactory<ISimpleService>(b);
                var c = f.CreateChannel(new EndpointAddress(address));
                using (f) { }
                c.Do();
            }
        }
 public void CreateMultipleChannelProxies()
 {
     string address = "net.pipe://localhost/";
     using (ServiceHost<TestService> host = new ServiceHost<TestService>())
     {
         host.AddServiceEndpoint<ITestContract>(new NetNamedPipeBinding(), address);
         host.Open();
         ITestContract proxy1 = host.CreateChannel<ITestContract>(new NetNamedPipeBinding(), address);
         ITestContract proxy2 = host.CreateChannel<ITestContract>(new NetNamedPipeBinding(), address);
         Assert.AreNotSame(proxy1, proxy2);
         Assert.AreEqual<string>("MyResult", proxy1.MyOperation());
         Assert.AreEqual<string>("MyResult", proxy2.MyOperation());
         ((ICommunicationObject)proxy1).Close();
         ((ICommunicationObject)proxy2).Close();
     }
 }
		static void SetupCustomPeerResolverServiceHost ()
		{
			// launch peer resolver service locally only when it does not seem to be running ...
			var t = new TcpListener (8931);
			try {
				t.Start ();
				t.Stop ();
			} catch {
				return;
			}
			Console.WriteLine ("WARNING: it is running peer resolver service locally. This means, the node registration is valid only within this application domain...");
			var host = new ServiceHost (new LocalPeerResolverService (TextWriter.Null));
			host.Description.Behaviors.Find<ServiceBehaviorAttribute> ().InstanceContextMode = InstanceContextMode.Single;
			host.AddServiceEndpoint (typeof (ICustomPeerResolverContract), new BasicHttpBinding (), "http://localhost:8931");
			localhost = host;
			host.Open ();
		}
Example #21
0
        static void Main(string[] args)
        {
            string service_url = "http://localhost:2020/manufacturerservice/a";
            ServiceHost host = new ServiceHost(typeof(manufacturerAServiceImplementation));
            host.AddServiceEndpoint(typeof(ImanufacturerAService), new BasicHttpBinding(), service_url);

            try
            {
                host.Open();
                Console.WriteLine();
                host.Close();
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                host.Abort();
            }
        }
        public void ReleaseInstanceModeBeforeTest()
        {
            Binding binding = new NetNamedPipeBinding();
            var address = "net.pipe://localhost/" + Guid.NewGuid();
            using (var host =
                new ServiceHost(typeof(MyService), new Uri(address)))
            {
                host.AddServiceEndpoint(typeof(IMyCounter), binding, "");
                host.Open();

                var proxy = ChannelFactory<IMyCounter>.CreateChannel(binding, new EndpointAddress(address));
                proxy.SetCount(3);
                Assert.AreEqual(3, proxy.GetCount());
                Assert.AreEqual(1, proxy.ReleaseBeforeIncrement());
                Assert.AreEqual(1, proxy.GetCount());
                ((ICommunicationObject)proxy).Close();
            }
        }
Example #23
0
        public void SingletonInitialization()
        {
            // Initialize Counter
            SingletonCounter myCounter = new SingletonCounter();
            myCounter.Counter = 5;

            string address = "http://localhost/" + Guid.NewGuid().ToString();
            Binding binding = new WSHttpBinding();
            using (ServiceHost host = new ServiceHost(myCounter))
            {
                // Host
                host.AddServiceEndpoint(typeof(ICounter), binding, address);
                host.Open();

                // Client
                ICounter counter = ChannelFactory<ICounter>.CreateChannel(binding, new EndpointAddress(address));
                counter.IncrementCounter();
                Assert.AreEqual(6, counter.GetCurrentValue());
                ((ICommunicationObject)counter).Close();
            }
        }
Example #24
0
        public void CallbackAsyncCallback_wait_done()
        {
            var address = @"net.pipe://127.0.0.1/" + this.GetType().Name + "_" + MethodBase.GetCurrentMethod().Name;
            var binding = new NetNamedPipeBinding();

            var srv = new AsyncService(null);
            var callback = new AsyncServiceCallback();

            using (var host = new ServiceHost(srv, new Uri(address)))
            {
                host.AddServiceEndpoint(typeof(IAsyncService), binding, address);
                host.Open();

                using (var factory = new DuplexChannelFactory<IAsyncService>(new InstanceContext(callback), binding))
                {
                    var client = factory.CreateChannel(new EndpointAddress(address));
                    client.DoSyncCall();

                }
            }
        }
Example #25
0
        public void IContextChannel_operationTimeoutSetGet_Ok()
        {
            var address = @"net.pipe://127.0.0.1/" + this.GetType().Name + "_" + MethodBase.GetCurrentMethod().Name;
            var binding = new NetNamedPipeBinding();
            using (var server = new ServiceHost(new SimpleService(), new Uri(address)))
            {

                server.AddServiceEndpoint(typeof(ISimpleService), binding, address);
                server.Open();
                Thread.Sleep(100);
                using (var channelFactory = new ChannelFactory<ISimpleService>(binding))
                {
                    var client = channelFactory.CreateChannel(new EndpointAddress(address));
                    var contextChannel = client as IContextChannel;
                    var newTimeout = TimeSpan.FromSeconds(123);
                    contextChannel.OperationTimeout = newTimeout;
                    var timeout = contextChannel.OperationTimeout;
                    Assert.AreEqual(newTimeout, timeout);

                }
            }
        }
        public void TestSetThrottle()
        {
            NetNamedPipeBinding binding = new NetNamedPipeBinding();
            string address = "net.pipe://localhost/" + Guid.NewGuid().ToString();

            using (ServiceHost<ThrottledService> host = new ServiceHost<ThrottledService>(address)) {
                host.AddServiceEndpoint<IThrottlingInformation>(binding, "");
                host.SetThrottle(12, 34, 56);
                host.Open();

                IThrottlingInformation service = ChannelFactory<IThrottlingInformation>.CreateChannel(
                    binding,
                    new EndpointAddress(address));

                using (service as IDisposable) {
                    ThrottleInfo info = service.GetThrottleInfo();
                    Assert.AreEqual(12, info.MaxConcurrentCalls);
                    Assert.AreEqual(34, info.MaxConcurrentSessions);
                    Assert.AreEqual(56, info.MaxConcurrentInstances);
                }
            }
        }
Example #27
0
        public void OneWayCall()
        {
            string address = "net.pipe://localhost/" + Guid.NewGuid().ToString();
            using (ServiceHost<MyService> host = new ServiceHost<MyService>())
            {
                host.AddServiceEndpoint<IMyContract>(new NetNamedPipeBinding(), address);
                host.OpenTimeout = new TimeSpan(0, 0, 30);
                host.Open();

                IMyContract service = ChannelFactory<IMyContract>.CreateChannel(new NetNamedPipeBinding(), new EndpointAddress(address));
                ICommunicationObject comm = (ICommunicationObject)service;
                Assert.AreEqual(CommunicationState.Created, comm.State);

                service.OneWayCall();
                Assert.AreEqual(CommunicationState.Opened, comm.State);

                // Call causes exception inside service that silently terminates
                service.ThrowException();
                try
                {
                    // Subsequent calls fails
                    service.OneWayCall();
                    // This is why Juval believes one-way operations on sessionful
                    // services is a bad design.  Here the client doesn't know that
                    // the serivce is in a faulted state until the next call.
                }
                catch (CommunicationException) { };

                Assert.AreEqual(CommunicationState.Faulted, comm.State);

                try
                {
                    // Cannot close because the connection is in a faulted state.
                    ((ICommunicationObject)service).Close();
                    Assert.Fail("Expected Close() to fail.");
                }
                catch (CommunicationObjectFaultedException) { };
            }
        }
Example #28
0
        public void TpcIp()
        {
            var address = @"net.tcp://127.0.0.1:18080";
            var serv = new Service(null);
            var host = new ServiceHost(serv, new Uri(address));
            var b = new NetTcpBinding();
            host.AddServiceEndpoint(typeof(IService), b, address);
            host.Open();
            var f = new ChannelFactory<IService>(b);
            var c = f.CreateChannel(new EndpointAddress(address));

            var result = c.DoWithParamsAndResult(":)", Guid.NewGuid());
            Assert.AreEqual(2, result.d1);
            host.Dispose();
        }
Example #29
0
        private static void InitServiceHost()
        {
            Uri tcpAdrs = new Uri("net.tcp://" +
                                  IP + ":" +
                                  PORT + "/Host/");

            Uri httpAdrs = new Uri("http://" +
                                   IP + ":" +
                                   (PORT + 1).ToString() +
                                   "/Host/");

            Uri[] baseAdresses = { tcpAdrs, httpAdrs };

            host = new ServiceHost(typeof(POGApp.POGService), baseAdresses);

            NetTcpBinding tcpBinding = new NetTcpBinding(SecurityMode.None, true)
            {
                MaxBufferPoolSize      = 67108864,
                MaxBufferSize          = 67108864,
                MaxReceivedMessageSize = 67108864,
                TransferMode           = TransferMode.Buffered
            };

            tcpBinding.ReaderQuotas.MaxArrayLength         = 67108864;
            tcpBinding.ReaderQuotas.MaxBytesPerRead        = 67108864;
            tcpBinding.ReaderQuotas.MaxStringContentLength = 67108864;


            tcpBinding.MaxConnections = 100;
            //To maxmize MaxConnections you have
            //to assign another port for mex endpoint

            //and configure ServiceThrottling as well
            ServiceThrottlingBehavior throttle = host.Description.Behaviors.Find <ServiceThrottlingBehavior>();

            if (throttle == null)
            {
                throttle = new ServiceThrottlingBehavior
                {
                    MaxConcurrentCalls    = 100,
                    MaxConcurrentSessions = 100
                };
                host.Description.Behaviors.Add(throttle);
            }


            //Enable reliable session and keep
            //the connection alive for 20 hours.
            tcpBinding.ReceiveTimeout                    = new TimeSpan(20, 0, 0);
            tcpBinding.ReliableSession.Enabled           = true;
            tcpBinding.ReliableSession.InactivityTimeout = new TimeSpan(20, 0, 10);

            host.AddServiceEndpoint(typeof(POGApp.IPOGService), tcpBinding, "tcp");

            //Define Metadata endPoint, So we can
            //publish information about the service
            ServiceMetadataBehavior mBehave = new ServiceMetadataBehavior();

            host.Description.Behaviors.Add(mBehave);

            host.AddServiceEndpoint(typeof(IMetadataExchange),
                                    MetadataExchangeBindings.CreateMexTcpBinding(),
                                    "net.tcp://" + IP + ":" +
                                    (PORT - 1).ToString() +
                                    "/Host/mex");


            try
            {
                host.Open();
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error opening host: " + ex);
            }
            finally
            {
                if (host.State == CommunicationState.Opened)
                {
                    Console.WriteLine("Opened");
                    //labelStatus.Content = "Opened";
                    //buttonStop.IsEnabled = true;
                }
            }
        }
Example #30
0
        public void Run(IObserver observer)
        {
            IPAddress hostIP = Dns.GetHostEntry(Dns.GetHostName()).AddressList[0];

            foreach (IPAddress ip in Dns.GetHostEntry(Dns.GetHostName()).AddressList)
            {
                if (ip.ToString().Substring(0, 3) == "192") //local
                ////if (ip.ToString().Substring(0, 3) == "134") //exclusively for saarland university
                {
                    hostIP = ip;
                    break;
                }
            }

            observer.setIP(hostIP);
            Uri address;

            if (showmdata)
            {
                address = new Uri(string.Format("http://localhost:8000/kanji", hostIP.ToString()));
                Console.WriteLine("Discovery mode");
            }

            else
            {
                address = new Uri(string.Format("http://{0}:8000/kanji", hostIP.ToString()));
                Console.WriteLine("NOT Discovery mode");
            }

            KanjiService knsvc = new KanjiService();

            knsvc.RegisterObserver(observer);

            //ServiceHost serviceHost = new ServiceHost(typeof(KanjiService), address);

            ServiceHost serviceHost = new ServiceHost((object)knsvc, address);

            //if (serviceHost.SingletonInstance is KanjiService)
            //    Console.WriteLine("is a kanjiservice");

            try
            {
                serviceHost.AddServiceEndpoint(
                    typeof(IKanjiService),
                    new BasicHttpBinding(),
                    "KanjiService");

                if (showmdata)
                {
                    // Enable metadata exchange - this is needed for NetCfSvcUtil to discover us
                    ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
                    smb.HttpGetEnabled = true;
                    serviceHost.Description.Behaviors.Add(smb);
                    Console.WriteLine("Metadata published");
                }
                else
                {
                    Console.WriteLine("Metadata NOT published");
                }
                serviceHost.Open();

                Console.WriteLine("KanjiService is running at " + address.ToString());
                //Console.WriteLine("KanjiService is running at " + Dns.GetHostEntry(Dns.GetHostName()).AddressList[0].ToString());
                //Console.WriteLine("Press <ENTER> to terminate");
                int i = Int32.MaxValue / 2;
                while (true)
                {
                    if (i-- == 0)
                    {
                        Thread.Sleep(1000);

                        i = Int32.MaxValue / 2;
                    }
                }
                //Console.ReadLine();

                // Close the ServiceHostBase to shutdown the service.
                //serviceHost.Close();
            }
            catch (CommunicationException ce)
            {
                Console.WriteLine("An exception occured: {0}", ce.Message);
                serviceHost.Abort();
            }
            catch (ThreadAbortException te)
            {
                Console.WriteLine("An exception occured: {0}", te.Message);
                try
                {
                    serviceHost.Close(new TimeSpan(0, 0, 1));
                }
                catch
                {
                    serviceHost.Abort();
                }
            }
        }
        public static void StartService()
        {
            //Create the Service host
            host = new ServiceHost(typeof(DataSelectionService));

            // Set binding max size and timeout
            NetTcpBinding netTcpBinding = new NetTcpBinding();

            netTcpBinding.SendTimeout            = netTcpBinding.ReceiveTimeout = TimeSpan.FromMinutes(120);
            netTcpBinding.MaxBufferPoolSize      = int.MaxValue; // 2147483647;
            netTcpBinding.MaxReceivedMessageSize = int.MaxValue; // 2147483647;
            netTcpBinding.MaxBufferSize          = int.MaxValue; // 2147483647;

            netTcpBinding.ReaderQuotas.MaxArrayLength        = int.MaxValue;
            netTcpBinding.ReaderQuotas.MaxBytesPerRead       = int.MaxValue;
            netTcpBinding.ReaderQuotas.MaxDepth              = int.MaxValue;
            netTcpBinding.ReaderQuotas.MaxNameTableCharCount = int.MaxValue;

            //Add the endpoint
            try
            {
                host.AddServiceEndpoint(new ServiceEndpoint(
                                            ContractDescription.GetContract(typeof(IDataSelectionService)),
                                            netTcpBinding,
                                            new EndpointAddress(Properties.Settings.Default.DataSelectionServiceAddress)));

                foreach (ServiceEndpoint ep in host.Description.Endpoints)
                {
                    foreach (OperationDescription op in ep.Contract.Operations)
                    {
                        DataContractSerializerOperationBehavior dataContractBehavior = op.Behaviors[typeof(DataContractSerializerOperationBehavior)] as DataContractSerializerOperationBehavior;

                        if (dataContractBehavior != null)
                        {
                            dataContractBehavior.MaxItemsInObjectGraph = int.MaxValue;
                        }
                    }
                }

                //if (Logger.IsDebugEnabled())
                //    Logger.Log(LogLevel.DEBUG, "EndPoint added to Service Host");
            }
            catch (Exception e)
            {
                //if (Logger.IsErrorEnabled())
                //    Logger.Log(LogLevel.ERROR, "An error occurred adding Service Host EndPoint", e);
                throw;
            }

            //Open the service
            try
            {
                host.Open();
                //if (Logger.IsInfoEnabled())
                //    Logger.Log(LogLevel.INFO, "Service Host opened");
            }
            catch (Exception e)
            {
                //if (Logger.IsErrorEnabled())
                //    Logger.Log(LogLevel.ERROR, "An error occurred opening Service Host", e);
                throw;
            }
        }
        public void ConfigureServiceHost(ServiceHost host, ServiceHostConfigurationArgs args)
        {
            var settings = new EnterpriseImageServerServiceSettings();

            // Per MSDN: Transport security is provided externally to WCF. If you are creating a self-hosted WCF application, you can bind an SSL certificate to the address using the HttpCfg.exe tool.
            // The service may appears running but client will not be able to connect. For this reason, it's best to explicitly disallow this mode.
            if (settings.SecurityMode == SecurityMode.Transport)
            {
                throw new Exception("Transport security is not supported. Please change EnterpriseImageServerServiceSettings.SecurityMode");
            }


            var binding = new WSHttpBinding
            {
                MaxReceivedMessageSize = args.MaxReceivedMessageSize
            };

            if (args.SendTimeoutSeconds > 0)
            {
                binding.SendTimeout = TimeSpan.FromSeconds(args.SendTimeoutSeconds);
            }

            binding.ReaderQuotas.MaxStringContentLength = args.MaxReceivedMessageSize;
            binding.ReaderQuotas.MaxArrayLength         = args.MaxReceivedMessageSize;
            binding.Security.Mode = settings.SecurityMode;
            binding.Security.Message.ClientCredentialType = args.Authenticated
                                                                                ? MessageCredentialType.UserName
                                                                                : MessageCredentialType.None;


            // TransportWithMessageCredential cannot be used in conjuction with ClientCredentialType=None
            if (binding.Security.Mode == SecurityMode.TransportWithMessageCredential &&
                binding.Security.Message.ClientCredentialType == MessageCredentialType.None)
            {
                throw new Exception(string.Format("TransportWithMessageCredential is not supported for '{0}' service. Please change EnterpriseImageServerServiceSettings.SecurityMode", args.ServiceContract.Name));
            }


            // establish endpoint
            host.AddServiceEndpoint(args.ServiceContract, binding, "");

            // expose meta-data via HTTP GET
            var metadataBehavior = host.Description.Behaviors.Find <ServiceMetadataBehavior>();

            if (metadataBehavior == null)
            {
                metadataBehavior = new ServiceMetadataBehavior
                {
                    HttpGetEnabled = true
                };
                host.Description.Behaviors.Add(metadataBehavior);
            }

            //TODO (Rockstar): remove this after refactoring to do per-sop edits
            foreach (var endpoint in host.Description.Endpoints)
            {
                foreach (var operation in endpoint.Contract.Operations)
                {
                    operation.Behaviors.Find <DataContractSerializerOperationBehavior>().MaxItemsInObjectGraph = args.MaxReceivedMessageSize;
                }
            }

            // set up the certificate
            if (settings.SecurityMode == SecurityMode.Message ||
                settings.SecurityMode == SecurityMode.TransportWithMessageCredential)
            {
                host.Credentials.ServiceCertificate.SetCertificate(
                    StoreLocation.LocalMachine, StoreName.My, X509FindType.FindBySubjectName, args.HostUri.Host);
            }
        }
Example #33
0
 private void btn_stop_Click(object sender, EventArgs e)
 {
     host.Close();
     host = new ServiceHost(typeof(Service1));
     host.AddServiceEndpoint(typeof(IService1), new BasicHttpBinding(), "");
 }
Example #34
0
        internal void StartServer()
        {
            if (IsServerRunning)
            {
                return;
            }

            Binding binding = GetTargetBinding();

            if (binding == null)
            {
                ASF.ArchiLogger.LogNullError(nameof(binding));
                return;
            }

            string url = GetUrlFromBinding(binding);

            if (string.IsNullOrEmpty(url))
            {
                ASF.ArchiLogger.LogNullError(nameof(url));
                return;
            }

            ASF.ArchiLogger.LogGenericInfo(string.Format(Strings.WCFStarting, url));

            Uri uri;

            try {
                uri = new Uri(url);
            } catch (UriFormatException e) {
                ASF.ArchiLogger.LogGenericException(e);
                return;
            }

            ServiceHost = new ServiceHost(typeof(WCF), uri);

            ServiceHost.AddServiceEndpoint(
                typeof(IWCF),
                binding,
                string.Empty
                );

            ServiceMetadataBehavior smb = new ServiceMetadataBehavior();

            switch (binding.Scheme)
            {
            case "http":
                smb.HttpGetEnabled = true;
                break;

            case "https":
                smb.HttpsGetEnabled = true;
                break;

            case "net.tcp":
                break;

            default:
                ASF.ArchiLogger.LogGenericWarning(string.Format(Strings.WarningUnknownValuePleaseReport, nameof(binding.Scheme), binding.Scheme));
                goto case "net.tcp";
            }

            ServiceHost.Description.Behaviors.Add(smb);

            try {
                ServiceHost.Open();
            } catch (AddressAccessDeniedException) {
                ASF.ArchiLogger.LogGenericError(Strings.ErrorWCFAddressAccessDeniedException);
                return;
            } catch (Exception e) {
                ASF.ArchiLogger.LogGenericException(e);
                return;
            }

            ASF.ArchiLogger.LogGenericInfo(Strings.WCFReady);
        }
Example #35
0
        private async Task <ResultStatus> StartCommand(IExecuteContext executeContext, ListStore <CommandResultEntry> commandResultEntries, BuilderContext builderContext)
        {
            var logger = executeContext.Logger;

            // Register the cancel callback
            var cancellationTokenSource = executeContext.CancellationTokenSource;

            cancellationTokenSource.Token.Register(x => ((Command)x).Cancel(), Command);

            Command.CancellationToken = cancellationTokenSource.Token;

            //await Scheduler.Yield();

            ResultStatus status;

            using (commandResultEntries)
            {
                logger.Debug("Starting command {0}...", Command.ToString());

                // Creating the CommandResult object
                var commandContext = new LocalCommandContext(executeContext, this, builderContext);

                // Actually processing the command
                if (Command.ShouldSpawnNewProcess() && builderContext.MaxParallelProcesses > 0)
                {
                    while (!builderContext.CanSpawnParallelProcess())
                    {
                        await Task.Delay(1, Command.CancellationToken);
                    }

                    var address   = "net.pipe://localhost/" + Guid.NewGuid();
                    var arguments = string.Format("--slave=\"{0}\" --build-path=\"{1}\" --profile=\"{2}\"", address, builderContext.BuildPath, builderContext.BuildProfile);

                    var startInfo = new ProcessStartInfo
                    {
                        FileName               = builderContext.SlaveBuilderPath,
                        Arguments              = arguments,
                        WorkingDirectory       = Environment.CurrentDirectory,
                        CreateNoWindow         = true,
                        UseShellExecute        = false,
                        RedirectStandardOutput = true,
                        RedirectStandardError  = true,
                    };

                    // Start WCF pipe for communication with process
                    var processBuilderRemote = new ProcessBuilderRemote(commandContext, Command, builderContext.Parameters);
                    var host = new ServiceHost(processBuilderRemote);
                    host.AddServiceEndpoint(typeof(IProcessBuilderRemote), new NetNamedPipeBinding(NetNamedPipeSecurityMode.None)
                    {
                        MaxReceivedMessageSize = int.MaxValue
                    }, address);
                    host.Open();

                    var output = new List <string>();

                    var process = new Process {
                        StartInfo = startInfo
                    };
                    process.Start();
                    process.OutputDataReceived += (_, args) => LockProcessAndAddDataToList(process, output, args);
                    process.ErrorDataReceived  += (_, args) => LockProcessAndAddDataToList(process, output, args);
                    process.BeginOutputReadLine();
                    process.BeginErrorReadLine();

                    // Attach debugger to newly created process
                    // Add a reference to EnvDTE80 in the csproj and uncomment this (and also the Thread.Sleep in BuildEngineCmmands), then start the master process without debugger to attach to a slave.
                    //var dte = (EnvDTE80.DTE2)System.Runtime.InteropServices.Marshal.GetActiveObject("VisualStudio.DTE.11.0");
                    //foreach (EnvDTE.Process dteProcess in dte.Debugger.LocalProcesses)
                    //{
                    //    if (dteProcess.ProcessID == process.Id)
                    //    {
                    //        dteProcess.Attach();
                    //        dte.Debugger.CurrentProcess = dteProcess;
                    //    }
                    //}

                    Task[] tasksToWait = null;

                    while (!process.HasExited)
                    {
                        Thread.Sleep(1);
                        lock (spawnedCommandsToWait)
                        {
                            if (spawnedCommandsToWait.Count > 0)
                            {
                                tasksToWait = spawnedCommandsToWait.ToArray();
                                spawnedCommandsToWait.Clear();
                            }
                        }

                        if (tasksToWait != null)
                        {
                            await Task.WhenAll(tasksToWait);

                            tasksToWait = null;
                        }
                    }
                    host.Close();

                    builderContext.NotifyParallelProcessEnded();

                    if (process.ExitCode != 0)
                    {
                        logger.Debug("Remote command crashed with output:\n{0}", string.Join(Environment.NewLine, output));
                    }

                    if (processBuilderRemote.Result != null)
                    {
                        // Register results back locally
                        foreach (var outputObject in processBuilderRemote.Result.OutputObjects)
                        {
                            commandContext.RegisterOutput(outputObject.Key, outputObject.Value);
                        }

                        // Register tags
                        foreach (var tag in processBuilderRemote.Result.TagSymbols)
                        {
                            TagSymbol tagSymbol;

                            // Resolve tag locally
                            if (!Command.TagSymbols.TryGetValue(tag.Value, out tagSymbol))
                            {
                                // Should we ignore silently? (with warning)
                                throw new InvalidOperationException("Could not find tag symbol.");
                            }

                            commandContext.AddTag(tag.Key, tagSymbol);
                        }
                    }

                    status = Command.CancellationToken.IsCancellationRequested ? ResultStatus.Cancelled : (process.ExitCode == 0 ? ResultStatus.Successful : ResultStatus.Failed);
                }
                else
                {
                    Command.PreCommand(commandContext);
                    if (!Command.BasePreCommandCalled)
                    {
                        throw new InvalidOperationException("base.PreCommand not called in command " + Command);
                    }

                    status = await Command.DoCommand(commandContext);

                    Command.PostCommand(commandContext, status);
                    if (!Command.BasePostCommandCalled)
                    {
                        throw new InvalidOperationException("base.PostCommand not called in command " + Command);
                    }
                }

                // Ensure the command set at least the result status
                if (status == ResultStatus.NotProcessed)
                {
                    throw new InvalidDataException("The command " + Command + " returned ResultStatus.NotProcessed after completion.");
                }

                // Registering the result to the build cache
                RegisterCommandResult(commandResultEntries, commandContext.ResultEntry, status);
            }

            return(status);
        }
Example #36
0
        /// <summary>
        /// see IDataServerServiceHost interface
        /// </summary>
        public void Start(Dictionary <string, object> args)
        {
            //configure wcf
            string localIp          = null;
            int    port             = 0;
            int    design_time_port = 0;

            WriteToLog_Info("Service host starting...", null);
            if (args.ContainsKey("ip"))
            {
                localIp = args["ip"] as string;
            }
            if (localIp == null)
            {
                throw new Exception("WCF session manager can not start because 'ip' parameter is not specified");
            }
            if (args.ContainsKey("port"))
            {
                Int32.TryParse(args["port"].ToString(), out port);
            }
            if (port == 0)
            {
                throw new Exception("WCF session manager can not start because 'port' parameter is not specified");
            }
            if (args.ContainsKey("design_time_port"))
            {
                Int32.TryParse(args["design_time_port"].ToString(), out design_time_port);
            }

            TimeSpan   timeOut = new TimeSpan(0, 1, 0);
            List <Uri> aURIs   = new List <Uri>();

            aURIs.Add(new Uri(string.Format("net.tcp://{0}:{1}/DataServer_Service", localIp, port)));
            if (design_time_port != 0)
            {
                aURIs.Add(new Uri(string.Format("http://{0}:{1}/DataServer_Service", localIp, design_time_port)));
            }

            NetTcpBinding binding = new NetTcpBinding();

            binding.TransactionFlow = false;
            binding.Security.Transport.ProtectionLevel      = System.Net.Security.ProtectionLevel.EncryptAndSign;
            binding.Security.Transport.ClientCredentialType = TcpClientCredentialType.Windows;
            binding.ReceiveTimeout = timeOut;
            binding.SendTimeout    = timeOut;
            binding.OpenTimeout    = timeOut;
            binding.CloseTimeout   = timeOut;
            binding.ReliableSession.InactivityTimeout = timeOut;
            binding.Security.Mode          = SecurityMode.None;
            binding.MaxBufferSize          = 1073741823;
            binding.MaxReceivedMessageSize = 1073741823;
            // start WCF service
            m_ServiceCore = new DataServerWCFService(this.Name);
            m_ServiceCore.Start();
            m_ServiceHost = new ServiceHost(m_ServiceCore, aURIs.ToArray());
            m_ServiceHost.AddServiceEndpoint(typeof(IWCFService), binding, aURIs[0]);
            m_ServiceHost.Description.Behaviors.Add(new ServiceMetadataBehavior());
            if (design_time_port != 0)
            {
                m_ServiceHost.AddServiceEndpoint(typeof(IMetadataExchange), MetadataExchangeBindings.CreateMexHttpBinding(), "mex");
            }

            m_ServiceHost.Open();
            WriteToLog_Info("Service host started.", null);
        }
Example #37
0
        /// <summary>
        /// Creates a new <see cref="ServiceHost"/> from the URI.
        /// </summary>
        /// <param name="serviceType">Specifies the type of WCF service to host.</param>
        /// <param name="baseAddresses">An array of base addresses for the service.</param>
        /// <returns>New <see cref="ServiceHost"/>.</returns>
        protected override ServiceHost CreateServiceHost(Type serviceType, Uri[] baseAddresses)
        {
#if MONO
            throw new NotSupportedException("Not supported under Mono.");
#else
            // Check security requirement.
            bool integratedSecurity = (Service.GetAuthenticationSchemes(baseAddresses[0]) & AuthenticationSchemes.Anonymous) != AuthenticationSchemes.Anonymous;

            // Create service host.
            ServiceHost host = base.CreateServiceHost(serviceType, baseAddresses);

            // Enable meta-data publishing.
            if (m_publishMetadata)
            {
                ServiceMetadataBehavior metadataBehavior = host.Description.Behaviors.Find <ServiceMetadataBehavior>();

                if (metadataBehavior == null)
                {
                    metadataBehavior = new ServiceMetadataBehavior();
                    host.Description.Behaviors.Add(metadataBehavior);
                }

                metadataBehavior.HttpGetEnabled = true;
            }

            // Enable security on the service.
            if (!m_disableSecurity)
            {
                ServiceAuthorizationBehavior authorizationBehavior = host.Description.Behaviors.Find <ServiceAuthorizationBehavior>();

                if (authorizationBehavior == null)
                {
                    authorizationBehavior = new ServiceAuthorizationBehavior();
                    host.Description.Behaviors.Add(authorizationBehavior);
                }

                authorizationBehavior.PrincipalPermissionMode = PrincipalPermissionMode.Custom;
                List <IAuthorizationPolicy> policies = new List <IAuthorizationPolicy>();
                policies.Add((IAuthorizationPolicy)Activator.CreateInstance(m_authorizationPolicy));
                authorizationBehavior.ExternalAuthorizationPolicies = policies.AsReadOnly();
            }

            // Create endpoint and configure security. (Not supported on Mono)
            host.AddDefaultEndpoints();

            if (string.IsNullOrEmpty(m_protocol))
            {
                // Use the default endpoint.
                foreach (ServiceEndpoint endpoint in host.Description.Endpoints)
                {
                    BasicHttpBinding basicBinding = endpoint.Binding as BasicHttpBinding;
                    if (basicBinding != null)
                    {
                        // Default endpoint uses BasicHttpBinding.
                        if (integratedSecurity)
                        {
                            // Enable security.
                            basicBinding.Security.Mode = BasicHttpSecurityMode.TransportCredentialOnly;
                            basicBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Windows;
                        }
                        else
                        {
                            // Disable security.
                            basicBinding.Security.Mode = BasicHttpSecurityMode.None;
                            basicBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.None;
                        }
                        foreach (IEndpointBehavior behavior in m_endpointBehaviors ?? new List <IEndpointBehavior>())
                        {
                            endpoint.Behaviors.Add(behavior);
                        }
                    }
                }
            }
            else
            {
                // Create endpoint using the specifics.
                host.Description.Endpoints.Clear();

                Binding         serviceBinding;
                ServiceEndpoint serviceEndpoint;
                serviceBinding = Service.CreateServiceBinding(ref m_protocol, integratedSecurity);

                if (serviceBinding != null)
                {
                    // Binding created for the endpoint.
                    Type contract = Service.GetServiceContract(serviceType);
                    if (!string.IsNullOrEmpty(m_address))
                    {
                        serviceEndpoint = host.AddServiceEndpoint(contract, serviceBinding, m_address);
                    }
                    else
                    {
                        serviceEndpoint = host.AddServiceEndpoint(contract, serviceBinding, string.Empty);
                    }

                    // Special handling for REST endpoint.
                    if (serviceBinding is WebHttpBinding)
                    {
                        WebHttpBehavior restBehavior = new WebHttpBehavior();
                        //#if !MONO
                        if (m_publishMetadata)
                        {
                            restBehavior.HelpEnabled = true;
                        }
                        //#endif
                        serviceEndpoint.Behaviors.Add(restBehavior);
                        serviceEndpoint.Behaviors.Add(new FormatSpecificationBehavior());
                    }

                    foreach (IEndpointBehavior behavior in m_endpointBehaviors ?? new List <IEndpointBehavior>())
                    {
                        serviceEndpoint.Behaviors.Add(behavior);
                    }
                }
            }

            foreach (var behavior in ServiceBehaviors ?? new List <IServiceBehavior>())
            {
                host.Description.Behaviors.Add(behavior);
            }

            return(host);
#endif
        }
        protected override void OnOpen(TimeSpan timeout)
        {
            DateTime start = DateTime.UtcNow;

            // FIXME: supply maxAddresses
            foreach (var a in resolver.Resolve(node.MeshId, 3, timeout))
            {
                peers.Add(new RemotePeerConnection(a));
            }

            // FIXME: pass more configuration
            var binding = new NetTcpBinding();

            binding.Security.Mode = SecurityMode.None;

            int port = 0;
            var rnd  = new Random();

            for (int i = 0; i < 1000; i++)
            {
                if (DateTime.UtcNow - start > timeout)
                {
                    throw new TimeoutException();
                }
                try {
                    port = rnd.Next(50000, 51000);
                    var t = new TcpListener(port);
                    t.Start();
                    t.Stop();
                    break;
                } catch (SocketException) {
                    continue;
                }
            }

            string name = Dns.GetHostName();
            var    uri  = new Uri("net.tcp://" + name + ":" + port + "/PeerChannelEndpoints/" + Guid.NewGuid());

            var peer_receiver = new LocalPeerReceiver(this);

            listener_host = new ServiceHost(peer_receiver);
            var sba = listener_host.Description.Behaviors.Find <ServiceBehaviorAttribute> ();

            sba.InstanceContextMode            = InstanceContextMode.Single;
            sba.IncludeExceptionDetailInFaults = true;

            var se = listener_host.AddServiceEndpoint(typeof(IPeerConnectorContract).FullName, binding, "net.p2p://" + node.MeshId + "/");

            se.ListenUri = uri;

            // FIXME: remove debugging code
            listener_host.UnknownMessageReceived += delegate(object obj, UnknownMessageReceivedEventArgs earg) { Console.WriteLine("%%%%% UNKOWN MESSAGE " + earg.Message); };

            listener_host.Open(timeout - (DateTime.UtcNow - start));

            var nid = (ulong)new Random().Next(0, int.MaxValue);
            var ea  = new EndpointAddress(uri);
            var pna = new PeerNodeAddress(ea, new ReadOnlyCollection <IPAddress> (Dns.GetHostEntry(name).AddressList));

            local_node_address = pna;
            node.RegisteredId  = resolver.Register(node.MeshId, pna, timeout - (DateTime.UtcNow - start));
            node.NodeId        = nid;

            // Add itself to the local list as well.
            // FIXME: it might become unnecessary once it implemented new node registration from peer resolver service.
            peers.Add(new RemotePeerConnection(pna));

            node.SetOnline();
        }
Example #39
0
        /// <summary>
        /// Try to start the RPC server
        /// </summary>
        public void StartService()
        {
#if !WCF
#warning "WCF functionality disabled - ServerList RPC will not function"
#else
            if (MasterServer.Settings.WebServerListenPort == 0)
            {
                return;
            }

            Uri uri = new Uri(String.Format("http://localhost:{0}/{1}/", MasterServer.Settings.WebServerListenPort, MasterServer.Settings.SyncServiceEndpoint));

            if (serviceHost == null)
            {
                try
                {
                    MasterServer.Log("[RPC] Starting service host");

                    // ServiceBinding for the RPC service
                    BasicHttpBinding ServiceBinding = new BasicHttpBinding(BasicHttpSecurityMode.TransportCredentialOnly);
                    ServiceBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Basic;

                    // Host for the RPC service
                    serviceHost = new ServiceHost(this, uri);

                    // Add local endpoint
                    serviceHost.AddServiceEndpoint(typeof(IServerList), ServiceBinding, MasterServer.Settings.SyncServiceName);

                    // Set up custom authentication
                    serviceHost.Credentials.UserNameAuthentication.UserNamePasswordValidationMode  = UserNamePasswordValidationMode.Custom;
                    serviceHost.Credentials.UserNameAuthentication.CustomUserNamePasswordValidator = new RPCCredentialValidator();

                    // Enable WSDL fetch functionality over HTTP
                    ServiceMetadataBehavior remoteServiceHostMetaDataBehaviour = new ServiceMetadataBehavior();
                    remoteServiceHostMetaDataBehaviour.HttpGetEnabled = true;
                    serviceHost.Description.Behaviors.Add(remoteServiceHostMetaDataBehaviour);

                    // Disable the HTML help message (just return the WSDL to browser clients)
                    ServiceDebugBehavior remoteServiceHostDebugBehaviour = serviceHost.Description.Behaviors.Find <ServiceDebugBehavior>();
                    remoteServiceHostDebugBehaviour.HttpHelpPageEnabled = false;

                    // Open the service host
                    serviceHost.Open();

                    MasterServer.Log("[RPC] Initialised ok. Listening at {0}/{1}/{2}/", 80, MasterServer.Settings.SyncServiceEndpoint, MasterServer.Settings.SyncServiceName);
                }
                catch (AddressAlreadyInUseException)
                {
                    MasterServer.Log("[RPC] FAULT initialising listener: Port {0} already in use.", MasterServer.Settings.WebServerListenPort);
                }
                catch (CommunicationObjectFaultedException ex)
                {
                    MasterServer.Log("[RPC] FAULT initialising listener: {0}", ex.Message);
                }
                catch (TimeoutException ex)
                {
                    MasterServer.Log("[RPC] TIMEOUT initialising listener: {0}", ex.Message);
                }
                catch (InvalidOperationException)
                {
                    MasterServer.Log("[RPC] Error initialising listener, invalid operation.");
                }
                catch (ArgumentNullException)
                {
                    MasterServer.Log("[RPC] Error initialising listener, configuration error.");
                }
                catch (ArgumentOutOfRangeException)
                {
                    MasterServer.Log("[RPC] Error initialising listener, configuration error.");
                }
            }
#endif
        }
Example #40
0
        static void Main(string[] args)
        {
            try
            {
                var    address    = "net.tcp://{0}:{1}/QLKHDataService";
                string hostName   = ConfigurationManager.AppSettings["HostNameOrIP"];
                string portNumber = ConfigurationManager.AppSettings["PortNumber"];

                // Define the base address for the service
                var baseAddress = new Uri(string.Format(address, hostName, portNumber));

                // Create service host for the CalculatorService type and privide the base address
                using (var serviceHost = new ServiceHost(typeof(QLKHDataService), baseAddress))
                {
                    var smb = serviceHost.Description.Behaviors.Find <ServiceMetadataBehavior>();

                    if (smb == null)
                    {
                        smb = new ServiceMetadataBehavior
                        {
                            HttpGetEnabled   = false,
                            HttpsGetEnabled  = false,
                            MetadataExporter = { PolicyVersion = PolicyVersion.Policy15 }
                        };

                        ServiceThrottlingBehavior throttle = serviceHost.Description.Behaviors.Find <ServiceThrottlingBehavior>();
                        if (throttle == null)
                        {
                            throttle = new ServiceThrottlingBehavior
                            {
                                MaxConcurrentCalls     = 1000,
                                MaxConcurrentSessions  = 1000,
                                MaxConcurrentInstances = 1000
                            };
                            serviceHost.Description.Behaviors.Add(throttle);
                        }

                        serviceHost.Description.Behaviors.Add(smb);
                    }

                    serviceHost.AddServiceEndpoint(ServiceMetadataBehavior.MexContractName, MetadataExchangeBindings.CreateMexTcpBinding(), "mex");

                    var binding = new NetTcpBinding
                    {
                        OpenTimeout            = new TimeSpan(1, 30, 0),
                        CloseTimeout           = new TimeSpan(1, 30, 0),
                        SendTimeout            = new TimeSpan(1, 30, 0),
                        ReceiveTimeout         = new TimeSpan(1, 30, 0),
                        MaxBufferSize          = int.MaxValue,
                        MaxReceivedMessageSize = int.MaxValue,
                        MaxBufferPoolSize      = int.MaxValue
                    };
                    binding.Security.Mode = SecurityMode.None;

                    serviceHost.AddServiceEndpoint(typeof(IQLKHDataService), binding, "");

                    serviceHost.Open();

                    // The service can now be accessed.
                    Console.WriteLine("The QLKH Data Service is ready. PORT : {0}", portNumber);
                    Console.WriteLine("Press <ENTER> to terminate service.");
                    Console.WriteLine();
                    Console.ReadLine();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.ReadLine();
            }
        }
Example #41
0
 private void Form1_Load(object sender, EventArgs e)
 {
     host = new ServiceHost(typeof(Service1));
     host.AddServiceEndpoint(typeof(IService1), new BasicHttpBinding(), "");
 }
Example #42
0
        static void Main(string[] args)
        {
            // <Snippet2>
            ServiceHost host = new ServiceHost(typeof(Service), new Uri("http://localhost:8000"));

            // </Snippet2>
            // <Snippet3>
            host.AddServiceEndpoint(typeof(IService), new BasicHttpBinding(), "Soap");
            // </Snippet3>
            // <Snippet4>
            ServiceEndpoint endpoint = host.AddServiceEndpoint(typeof(IService), new WebHttpBinding(), "Web");

            endpoint.Behaviors.Add(new WebHttpBehavior());
            // </Snippet4>

            try
            {
                // <Snippet5>
                host.Open();
                // </Snippet5>

                // <Snippet6>
                using (WebChannelFactory <IService> wcf = new WebChannelFactory <IService>(new Uri("http://localhost:8000/Web")))
                // </Snippet6>
                {
                    // <Snippet8>
                    IService channel = wcf.CreateChannel();

                    string s;

                    Console.WriteLine("Calling EchoWithGet by HTTP GET: ");
                    s = channel.EchoWithGet("Hello, world");
                    Console.WriteLine("   Output: {0}", s);

                    Console.WriteLine("");
                    Console.WriteLine("This can also be accomplished by navigating to");
                    Console.WriteLine("http://localhost:8000/Web/EchoWithGet?s=Hello, world!");
                    Console.WriteLine("in a web browser while this sample is running.");

                    Console.WriteLine("");

                    Console.WriteLine("Calling EchoWithPost by HTTP POST: ");
                    s = channel.EchoWithPost("Hello, world");
                    Console.WriteLine("   Output: {0}", s);
                    // </Snippet8>
                    Console.WriteLine("");
                }
                // <Snippet10>
                using (ChannelFactory <IService> scf = new ChannelFactory <IService>(new BasicHttpBinding(), "http://localhost:8000/Soap"))
                // </Snippet10>
                {
                    // <Snippet11>
                    IService channel = scf.CreateChannel();

                    string s;

                    Console.WriteLine("Calling EchoWithGet on SOAP endpoint: ");
                    s = channel.EchoWithGet("Hello, world");
                    Console.WriteLine("   Output: {0}", s);

                    Console.WriteLine("");

                    Console.WriteLine("Calling EchoWithPost on SOAP endpoint: ");
                    s = channel.EchoWithPost("Hello, world");
                    Console.WriteLine("   Output: {0}", s);
                    // </Snippet11>
                    Console.WriteLine("");
                }

                Console.WriteLine("Press [Enter] to terminate");
                Console.ReadLine();
                // <Snippet9>
                host.Close();
                // </Snippet9>
            }
            catch (CommunicationException cex)
            {
                Console.WriteLine("An exception occurred: {0}", cex.Message);
                host.Abort();
            }
        }
Example #43
0
        private void btnIniciar_Click(object sender, RoutedEventArgs e)
        {
            btnIniciar.IsEnabled = false;

            //Definir la dirección base para todas las conexiones
            Uri DireccionTCP = new Uri("net.tcp://" +
                                       txtIP.Text + ":" +
                                       txtPuerto.Text + "/ServicioChat/");

            Uri DireccionHTTP = new Uri("http://" +
                                        txtIP.Text + ":" +
                                        (int.Parse(txtPuerto.Text) + 1).ToString() +
                                        "/ServicioChat/");

            Uri[] DireccionesBase = { DireccionTCP, DireccionHTTP };

            //Instancia del servicio
            Servidor = new ServiceHost(
                typeof(ServicioChat), DireccionesBase);


            NetTcpBinding tcpEnlace =
                new NetTcpBinding(SecurityMode.None, true);

            //Habilitar la transferencia de archivos de 64 MB
            tcpEnlace.MaxBufferPoolSize                   = (int)67108864;
            tcpEnlace.MaxBufferSize                       = 67108864;
            tcpEnlace.MaxReceivedMessageSize              = (int)67108864;
            tcpEnlace.TransferMode                        = TransferMode.Buffered;
            tcpEnlace.ReaderQuotas.MaxArrayLength         = 67108864;
            tcpEnlace.ReaderQuotas.MaxBytesPerRead        = 67108864;
            tcpEnlace.ReaderQuotas.MaxStringContentLength = 67108864;

            tcpEnlace.MaxConnections = 100;


            //Configurar el número máximo de conexiones al servicio
            //lo cual incide en el comportamiento del mismo
            ServiceThrottlingBehavior controlServicio;

            controlServicio =
                Servidor.Description.Behaviors.Find <ServiceThrottlingBehavior>();
            if (controlServicio == null)
            {
                controlServicio = new ServiceThrottlingBehavior();
                controlServicio.MaxConcurrentCalls    = 100;
                controlServicio.MaxConcurrentSessions = 100;
                Servidor.Description.Behaviors.Add(controlServicio);
            }

            //Configurar confiabilidad y durabilidad de la sesión
            tcpEnlace.ReceiveTimeout                    = new TimeSpan(20, 0, 0);
            tcpEnlace.ReliableSession.Enabled           = true;
            tcpEnlace.ReliableSession.InactivityTimeout =
                new TimeSpan(20, 0, 10);

            Servidor.AddServiceEndpoint(typeof(IChat),
                                        tcpEnlace, "tcp");


            //Habilitar la publicación de metadatos del servicio
            ServiceMetadataBehavior mBehave =
                new ServiceMetadataBehavior();

            Servidor.Description.Behaviors.Add(mBehave);

            Servidor.AddServiceEndpoint(typeof(IMetadataExchange),
                                        MetadataExchangeBindings.CreateMexTcpBinding(),
                                        "net.tcp://" + txtIP.Text.ToString() + ":" +
                                        (int.Parse(txtPuerto.Text.ToString()) - 1).ToString() +
                                        "/ServicioChat/mex");
            // net.tcp://localhost:7996//ServicioChat/mex
            try
            {
                //Iniciar el servicio
                Servidor.Open();
            }
            catch (Exception ex)
            {
                //No se pudo iniciar el servicio
                lblEstado.Text       = ex.Message.ToString();
                btnIniciar.IsEnabled = true;
            }
            finally
            {
                //Mostrar estado del servicio si se pudo abrir
                if (Servidor.State == CommunicationState.Opened)
                {
                    lblEstado.Text       = "Abierto";
                    btnDetener.IsEnabled = true;
                }
            }
        }
Example #44
0
 public void AddSpeechHost(String uri)
 {
     _speechHost = new ServiceHost(typeof(RPC.Speech.SpeechService));
     _speechHost.AddServiceEndpoint(typeof(ISpeechService), _binding, _baseUri.ToString() + uri);
     _hosts.Add(_speechHost);
 }
Example #45
0
        private void _startServer()
        {
            LobbyServiceImpl gameService = null;
            ServiceHost      host        = null;
            IPAddress        serverIp    = tab1IpAddresses.SelectedItem as IPAddress;

            if (serverIp == null)
            {
                _Warn("Please select an IP address");
                return;
            }
            int portNumber;

            if (!int.TryParse(tab1Port.Text, out portNumber))
            {
                _Warn("Please enter a legal port number");
                return;
            }
            busyIndicator.BusyContent = Resources["Busy.LaunchServer"];
            busyIndicator.IsBusy      = true;

            //client.Start(isReplay, FileStream = file.open(...))
            BackgroundWorker worker      = new BackgroundWorker();
            bool             hasDatabase = (tab1EnableDb.IsChecked == true);

            worker.DoWork += (o, ea) =>
            {
                try
                {
                    ea.Result = false;
                    if (hasDatabase)
                    {
                        LobbyServiceImpl.EnableDatabase();
                    }
                    LobbyServiceImpl.HostingIp = serverIp;

                    host = new ServiceHost(typeof(LobbyServiceImpl));
                    //, new Uri[] { new Uri(string.Format("net.tcp://{0}:{1}/GameService", serverIp, portNumber)) });
                    var binding = new NetTcpBinding();
                    binding.Security.Mode = SecurityMode.None;
                    binding.Security.Transport.ClientCredentialType = TcpClientCredentialType.None;
                    binding.Security.Transport.ProtectionLevel      = ProtectionLevel.None;
                    binding.Security.Message.ClientCredentialType   = MessageCredentialType.None;
                    binding.MaxBufferPoolSize      = Misc.MaxBugReportSize;
                    binding.MaxBufferSize          = Misc.MaxBugReportSize;
                    binding.MaxReceivedMessageSize = Misc.MaxBugReportSize;
                    host.AddServiceEndpoint(typeof(ILobbyService), binding, string.Format("net.tcp://{0}:{1}/GameService", serverIp, portNumber));
                    host.Open();
                    ea.Result = true;
                }
                catch (Exception)
                {
                }
            };

            worker.RunWorkerCompleted += (o, ea) =>
            {
                busyIndicator.IsBusy = false;
                if ((bool)ea.Result)
                {
                    ServerPage serverPage = new ServerPage();
                    serverPage.Host        = host;
                    serverPage.GameService = gameService;
                    this.NavigationService.Navigate(serverPage);
                }
                else
                {
                    MessageBox.Show("Failed to launch server");
                }
                startButton.IsEnabled = true;
            };

            worker.RunWorkerAsync();
        }
Example #46
0
 public void AddCameraHost(String uri)
 {
     _cameraHost = new ServiceHost(typeof(Capture));
     _cameraHost.AddServiceEndpoint(typeof(IDuplexCapture), _binding, _baseUri.ToString() + uri);
     _hosts.Add(_cameraHost);
 }
Example #47
0
        public static void Main()
        {
            // <Snippet0>
            Uri         baseAddress = new Uri("http://localhost:8001/Simple");
            ServiceHost serviceHost = new ServiceHost(typeof(CalculatorService), baseAddress);

            serviceHost.AddServiceEndpoint(
                typeof(ICalculator),
                new WSHttpBinding(),
                "CalculatorServiceObject");

            // Enable Mex
            ServiceMetadataBehavior smb = new ServiceMetadataBehavior();

            smb.HttpGetEnabled = true;
            serviceHost.Description.Behaviors.Add(smb);

            serviceHost.Open();

            // <Snippet1>
            ContractDescription cd0 = new ContractDescription("ICalculator");
            // </Snippet1>
            // <Snippet2>
            ContractDescription cd1 = new ContractDescription("ICalculator", "http://www.tempuri.org");
            // </Snippet2>
            // <Snippet13>
            ContractDescription cd2 = ContractDescription.GetContract(typeof(ICalculator));
            // </Snippet13>
            // <Snippet14>
            CalculatorService   calcSvc = new CalculatorService();
            ContractDescription cd3     = ContractDescription.GetContract(typeof(ICalculator), calcSvc);
            // </Snippet14>
            // <Snippet15>
            ContractDescription cd4 = ContractDescription.GetContract(typeof(ICalculator), typeof(CalculatorService));
            // </Snippet15>
            ContractDescription cd = serviceHost.Description.Endpoints[0].Contract;

            Console.WriteLine("Displaying information for contract: {0}", cd.Name.ToString());

            // <Snippet3>
            KeyedByTypeCollection <IContractBehavior> behaviors = cd.Behaviors;

            Console.WriteLine("\tDisplay all behaviors:");
            foreach (IContractBehavior behavior in behaviors)
            {
                Console.WriteLine("\t\t" + behavior.ToString());
            }
            // </Snippet3>

            // <Snippet4>
            Type type = cd.CallbackContractType;
            // </Snippet4>

            // <Snippet5>
            string configName = cd.ConfigurationName;

            Console.WriteLine("\tConfiguration name: {0}", configName);
            // </Snippet5>

            // <Snippet6>
            Type contractType = cd.ContractType;

            Console.WriteLine("\tContract type: {0}", contractType.ToString());
            // </Snippet6>

            // <Snippet7>
            bool hasProtectionLevel = cd.HasProtectionLevel;

            if (hasProtectionLevel)
            {
                // <Snippet11>
                ProtectionLevel protectionLevel = cd.ProtectionLevel;
                Console.WriteLine("\tProtection Level: {0}", protectionLevel.ToString());
                // </Snippet11>
            }
            // </Snippet7>


            // <Snippet8>
            string name = cd.Name;

            Console.WriteLine("\tName: {0}", name);
            // </Snippet8>

            // <Snippet9>
            string namespc = cd.Namespace;

            Console.WriteLine("\tNamespace: {0}", namespc);
            // </Snippet9>

            // <Snippet10>
            OperationDescriptionCollection odc = cd.Operations;

            Console.WriteLine("\tDisplay Operations:");
            foreach (OperationDescription od in odc)
            {
                Console.WriteLine("\t\t" + od.Name);
            }
            // </Snippet10>

            // <Snippet12>
            SessionMode sm = cd.SessionMode;

            Console.WriteLine("\tSessionMode: {0}", sm.ToString());
            // </Snippet12>

            // <Snippet16>
            Collection <ContractDescription> inheretedContracts = cd.GetInheritedContracts();

            Console.WriteLine("\tInherited Contracts:");
            foreach (ContractDescription contractdescription in inheretedContracts)
            {
                Console.WriteLine("\t\t" + contractdescription.Name);
            }
            // </Snippet16>

            Console.WriteLine("The service is ready.");
            Console.WriteLine("Press <ENTER> to terminate service.");
            Console.WriteLine();
            Console.ReadLine();

            // Close the ServiceHostBase to shutdown the service.
            serviceHost.Close();
            // </Snippet0>
        }
Example #48
0
 public void AddSerialHost(String uri)
 {
     _serialHost = new ServiceHost(typeof(SerialService));
     _serialHost.AddServiceEndpoint(typeof(ISerialService), _binding, _baseUri.ToString() + uri);
     _hosts.Add(_serialHost);
 }
    protected override ServiceHost CreateServiceHost(Type serviceType, Uri[] baseAddresses)
    {
        //string[] urlTokens = baseAddresses[0].AbsolutePath.Split('/');
        //string version = urlTokens[1].ToUpper();

        //Type[] contractInterfaces = serviceType.GetInterfaces().Where(i => i.GetCustomAttributes(true).Where(a => a.GetType() == typeof(System.ServiceModel.ServiceContractAttribute)).Any()).ToArray();
        //Type contractType = contractInterfaces.Where(i => i.Namespace.ToUpper().Contains(version)).Single();
        Type contractType = typeof(ServiceDiscovery.IServiceRegistry);

        ServiceHost host = base.CreateServiceHost(serviceType, baseAddresses);

        WSHttpBinding wsHttpBinding = new WSHttpBinding();

        wsHttpBinding.SendTimeout            = new TimeSpan(0, 5, 0);
        wsHttpBinding.MaxReceivedMessageSize = Int32.MaxValue;
        wsHttpBinding.BypassProxyOnLocal     = true;
        wsHttpBinding.Security.Mode          = SecurityMode.None;
        //wsHttpBinding.TransactionFlow = true;
        //wsHttpBinding.ReaderQuotas.MaxStringContentLength = Int32.MaxValue;

        //ServiceEndpoint endpoint = host.AddServiceEndpoint(contractType, wsHttpBinding, "");

        WebHttpBinding webHttpBinding = new WebHttpBinding();

        webHttpBinding.Security.Mode = WebHttpSecurityMode.None;
        webHttpBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Windows;
        webHttpBinding.Security.Transport.ProxyCredentialType  = HttpProxyCredentialType.None;
        webHttpBinding.BypassProxyOnLocal = true;

        ServiceEndpoint endpoint = host.AddServiceEndpoint(contractType, webHttpBinding, "");

        WebHttpBehavior webHttpBehavior = new WebHttpBehavior();

        webHttpBehavior.DefaultOutgoingRequestFormat = WebMessageFormat.Json;
        //behavior.DefaultBodyStyle = WebMessageBodyStyle.Bare;
        webHttpBehavior.DefaultBodyStyle      = WebMessageBodyStyle.Wrapped;
        webHttpBehavior.FaultExceptionEnabled = true;

        endpoint.Behaviors.Add(webHttpBehavior);

        ServiceMetadataBehavior metadataBehaviour;

        if ((host.Description.Behaviors.Contains(typeof(ServiceMetadataBehavior))))
        {
            metadataBehaviour = (ServiceMetadataBehavior)host.Description.Behaviors[typeof(ServiceMetadataBehavior)];
        }
        else
        {
            metadataBehaviour = new ServiceMetadataBehavior();
            host.Description.Behaviors.Add(metadataBehaviour);
        }
        metadataBehaviour.HttpGetEnabled = true;

        ServiceDebugBehavior debugBehaviour;

        if (host.Description.Behaviors.Contains(typeof(ServiceDebugBehavior)))
        {
            debugBehaviour = (ServiceDebugBehavior)host.Description.Behaviors[typeof(ServiceDebugBehavior)];
        }
        else
        {
            debugBehaviour = new ServiceDebugBehavior();
            host.Description.Behaviors.Add(debugBehaviour);
        }
        debugBehaviour.IncludeExceptionDetailInFaults = true;

        return(host);
    }
Example #50
0
        static void Main(string[] args)
        {
            Settings.Load();
            Settings.Save();
            _handler += new EventHandler(Handler);
            SetConsoleCtrlHandler(_handler, true);

            for (int i = 0; i < args.Length; i++)
            {
                var group = Regex.Match(args[i], "[-]{1,2}(.*)").Groups[1];
                if (group.Success)
                {
                    switch (group.Value)
                    {
                    case "nokey":
                        OverridePublicKey = false;
                        break;

                    case "showconsole":
                        showConsole = true;
                        break;
                    }
                }
            }

            Logger.WriteLine("Made by FailedShack");
            SetConsoleVisibility(showConsole);
            Application.EnableVisualStyles();

            if (Settings.ShowUpdateNag)
            {
                Task.Run(async() =>
                {
                    JObject release;
                    try
                    {
                        release = await GithubUtil.GetRelease("FailedShack", "USBHelperLauncher", "latest");
                    }
                    catch
                    {
                        return;
                    }
                    string newVersion = (string)release["tag_name"];
                    string version    = GetVersion();
                    if (newVersion.CompareTo(version) > 0)
                    {
                        var updateNag       = new CheckboxDialog("New version found: " + newVersion + "\nCurrent version: " + version + "\nDo you want to open the download site?", "Do not show this again.", "Update Checker", MessageBoxButtons.YesNo, MessageBoxIcon.Information);
                        DialogResult result = updateNag.ShowDialog();
                        if (result == DialogResult.Yes)
                        {
                            Process.Start((string)release["html_url"]);
                        }
                        Settings.ShowUpdateNag = !updateNag.Checked;
                        Settings.Save();
                    }
                }).Wait();
            }

            if (Settings.ShowTranslateNag && Locale.ChosenLocale != LocaleProvider.DefaultLocale)
            {
                var localeInfo   = Locale.KnownLocales[Locale.ChosenLocale];
                var translateNag = MessageBox.Show(
                    string.Format("We are currently looking for volunteers to translate Wii U USB Helper to other languages. " +
                                  "You may be able to contribute by submitting translations for {0} on Crowdin.\nWould you like to open the site?", localeInfo.Name),
                    "Appeal to Translate", MessageBoxButtons.YesNo, MessageBoxIcon.Information);
                if (translateNag == DialogResult.Yes)
                {
                    Process.Start("https://crowdin.com/project/wii-u-usb-helper");
                }
                Settings.ShowTranslateNag = false;
                Settings.Save();
            }

            var certs = new DirectoryInfo("certs");

            if (certs.Exists)
            {
                foreach (var file in certs.EnumerateFiles().Where(x => x.Length > 0))
                {
                    try
                    {
                        Proxy.CertificateStore.Import(file.FullName);
                    }
                    catch (CryptographicException)
                    {
                        MessageBox.Show(string.Format("{0} is not a valid certificate file.", file.Name, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error));
                        Environment.Exit(-1);
                    }
                }
            }

            string hostsFile = GetHostsFile();

            if (File.Exists(hostsFile))
            {
                try
                {
                    Hosts = Hosts.Load(hostsFile);
                }
                catch (Exception e)
                {
                    MessageBox.Show("Could not load hosts file: " + e.Message, "Malformed hosts file", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    Hosts = new Hosts();
                }

                var conflicting = Proxy.GetConflictingHosts();
                if (!Settings.HostsExpert && conflicting.Count > 0)
                {
                    var hostsConflictWarning = new CheckboxDialog(
                        "The following hostnames specified in the hosts file are normally handled by USBHelperLauncher:\n\n" + string.Join("\n", conflicting) +
                        "\n\nIf you override them the program may not function properly." +
                        "\nDo you want to exclude them?", "Do not show this again.", "Conflicting hosts", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
                    DialogResult result = hostsConflictWarning.ShowDialog();
                    if (result == DialogResult.Yes)
                    {
                        Hosts.hosts = Hosts.hosts.Where(x => !conflicting.Contains(x.Key)).ToDictionary(x => x.Key, x => x.Value);
                    }
                    Settings.HostsExpert = hostsConflictWarning.Checked;
                    Settings.Save();
                }
            }
            else
            {
                Hosts = new Hosts();
                if (Settings.ShowHostsWarning)
                {
                    var hostsWarning = new CheckboxDialog(
                        "It appears you don't currently have a hosts redirector file. This file may be required to route obsolete hostnames to their correct destination.\n" +
                        "If you intended to use this feature, make sure a file named 'hosts.json' is located in the same directory as this executable.\n" +
                        "You may also use the built-in editor located in the Advanced section in the tray icon's context menu.", "Do not show this again.", "Hosts file missing", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    hostsWarning.ShowDialog();
                    Settings.ShowHostsWarning = !hostsWarning.Checked;
                    Settings.Save();
                }
            }

            try
            {
                Database.LoadFromDir(Path.Combine(GetLauncherPath(), "data"));
            }
            catch (FileNotFoundException e)
            {
                MessageBox.Show(e.Message + "\nMake sure this file is under the data directory.", "Initialization error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                Environment.Exit(-1);
            }

            if (!File.Exists("ver") || !File.Exists("WiiU_USB_Helper.exe"))
            {
                MessageBox.Show("Could not find Wii U USB Helper, please make sure this executable is in the correct folder.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                Environment.Exit(-1);
            }
            HelperVersion = File.ReadAllLines("ver")[0];

            // Ensure that the cached title key JSON files are valid
            string[] toCheck = { "3FFFD23A80F800ABFCC436A5EC8F7F0B94C728A4", "9C6DD14B8E3530B701BC4F1B77345DADB0C32020" };
            foreach (string file in toCheck)
            {
                string path = Path.Combine(GetInstallPath(), file);
                if (File.Exists(path))
                {
                    try
                    {
                        JToken.Parse(File.ReadAllText(path));
                    }
                    catch (JsonReaderException)
                    {
                        File.Delete(path);
                        Logger.WriteLine(string.Format("Removed bad cache file: {0}", file));
                    }
                }
            }

            // Make sure that FiddlerCore's key container can be accessed
            string keyContainer = FiddlerApplication.Prefs.GetStringPref("fiddler.certmaker.bc.KeyContainerName", "FiddlerBCKey");

            if (WinUtil.CSP.TryAcquire(keyContainer) == WinUtil.CSP.NTE_BAD_KEY_STATE)
            {
                WinUtil.CSP.Delete(keyContainer);
                Logger.WriteLine("Removed broken key container: {0}", keyContainer);
            }

            CertMaker.oCertProvider = new BCCertMaker.BCCertMaker(); // Don't try to load CertMaker.dll
            if (!Settings.ForceHttp && !CertMaker.rootCertExists() && !CertMaker.createRootCert())
            {
                MessageBox.Show("Creation of the interception certificate failed.", "Unable to generate certificate.", MessageBoxButtons.OK, MessageBoxIcon.Error);
                Environment.Exit(-1);
            }

            string executable = Path.Combine(GetLauncherPath(), "WiiU_USB_Helper.exe");

            var running = Process.GetProcessesByName("Patched").FirstOrDefault(p => p.GetMainModuleFileName().StartsWith(GetLauncherPath(), StringComparison.OrdinalIgnoreCase));

            if (running != default(Process))
            {
                DialogResult result = MessageBox.Show("An instance of Wii U USB Helper is already running.\nWould you like to close it?", "Already running", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation);
                if (result == DialogResult.No)
                {
                    Environment.Exit(0);
                }
                running.Kill();
            }

            Proxy.Start();

            // Update translations
            var dialog = new ProgressDialog();
            var worker = dialog.GetWorker();

            dialog.SetHeader("Updating translations...");
            new Thread(() => dialog.ShowDialog()).Start();
            Task.Run(async() =>
            {
                try
                {
                    if (await Locale.UpdateIfNeeded(dialog))
                    {
                        Logger.WriteLine("Updated translations: {0}", Settings.TranslationsBuild);
                    }
                    else
                    {
                        Logger.WriteLine("Translations were up to date.");
                    }
                }
                catch (Exception e)
                {
                    Logger.WriteLine("Could not update translations: {0}", e.Message);
                }
            }).Wait();

            ServiceHost host = new ServiceHost(typeof(LauncherService), new Uri("net.pipe://localhost/LauncherService"));

            host.AddServiceEndpoint(typeof(ILauncherService), new NetNamedPipeBinding(), "");
            host.Open();

            // Patching
            dialog.Invoke(new Action(() =>
            {
                dialog.SetStyle(ProgressBarStyle.Marquee);
                dialog.GetProgressBar().MarqueeAnimationSpeed = 30;
                dialog.SetHeader("Injecting...");
            }));
            var injector = new ModuleInitInjector(executable);

            executable = Path.Combine(GetLauncherPath(), "WiiU_USB_Helper_.exe");
            injector.Inject(executable);
            Logger.WriteLine("Injected module initializer.");
            dialog.Invoke(new Action(() => dialog.Close()));

            if (OverridePublicKey)
            {
                // Generate an RSA key pair for our donation keys
                using (var rsa = new RSACryptoServiceProvider(2048))
                {
                    rsaParams = rsa.ExportParameters(true);
                    PublicKey = rsa.ToXmlString(false);
                }
            }

            // Time to launch Wii U USB Helper
            SessionStart = DateTime.UtcNow;
            var startInfo = new ProcessStartInfo()
            {
                FileName              = executable,
                Arguments             = HelperVersion,
                UseShellExecute       = false,
                RedirectStandardError = true,
                StandardErrorEncoding = Encoding.Default
            };
            var process = new Process()
            {
                StartInfo = startInfo
            };

            process.EnableRaisingEvents = true;
            process.Exited += async(sender, e) =>
            {
                if (killed)
                {
                    return;
                }
                if (process.ExitCode != 0)
                {
                    Logger.WriteLine("Wii U USB Helper returned non-zero exit code 0x{0:x}:\n{1}", process.ExitCode, process.StandardError.ReadToEnd().Trim());;
                    var result = MessageBox.Show(string.Format("Uh-oh. Wii U USB Helper has crashed unexpectedly.\nDo you want to generate a debug log?\n\nError code: 0x{0:x}", process.ExitCode), "Error", MessageBoxButtons.YesNo, MessageBoxIcon.Error);
                    if (result == DialogResult.Yes)
                    {
                        await GenerateDebugLog();
                    }
                }
                Cleanup();
                Application.Exit();
            };
            process.Start();
            HelperProcess = process;

            if (Settings.DisableOptionalPatches)
            {
                Logger.WriteLine("Optional patches have been disabled.");
            }

            if (Settings.ForceHttp)
            {
                Logger.WriteLine("Requests will be proxied over plain HTTP.");
            }

            ContextMenu trayMenu   = new ContextMenu();
            MenuItem    dlEmulator = new MenuItem("Download Emulator");

            foreach (EmulatorConfiguration.Emulator emulator in Enum.GetValues(typeof(EmulatorConfiguration.Emulator)))
            {
                EmulatorConfiguration config = EmulatorConfiguration.GetConfiguration(emulator);
                dlEmulator.MenuItems.Add(config.GetName(), (sender, e) => OnDownloadEmulator(config));
            }
            MenuItem language = new MenuItem("Language")
            {
                RadioCheck = true
            };

            foreach (var lang in Locale.AvailableLocales)
            {
                language.MenuItems.Add(lang.Value.Native, (sender, e) =>
                {
                    Settings.Locale = lang.Key;
                    Settings.Save();
                    MessageBox.Show("Your language choice has been saved.\nPlease restart USBHelperLauncher for changes to take effect.", "Restart required", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }).Checked = lang.Key == Locale.ChosenLocale;
            }
            if (language.MenuItems.Count == 0)
            {
                language.MenuItems.Add("No translations found").Enabled = false;
            }
            MenuItem advanced = new MenuItem("Advanced");

            advanced.MenuItems.Add("Toggle Console", OnVisibilityChange);
            advanced.MenuItems.Add("Clear Install", OnClearInstall);
            advanced.MenuItems.Add("Generate Donation Key", OnGenerateKey).Enabled = OverridePublicKey;
            advanced.MenuItems.Add("Hosts Editor", OnOpenHostsEditor);
            advanced.MenuItems.Add("Export Sessions", OnExportSessions);
            trayMenu.MenuItems.Add("Exit", OnExit);
            trayMenu.MenuItems.Add("Check for Updates", OnUpdateCheck);
            trayMenu.MenuItems.Add("Report Issue", async(sender, e) => await GenerateDebugLog());
            trayMenu.MenuItems.Add(dlEmulator);
            trayMenu.MenuItems.Add(language);
            trayMenu.MenuItems.Add(advanced);
            trayIcon = new NotifyIcon
            {
                Text        = "Wii U USB Helper Launcher",
                Icon        = Icon.ExtractAssociatedIcon(Application.ExecutablePath),
                ContextMenu = trayMenu,
                Visible     = true
            };
            Application.Run();
        }
Example #51
0
        public FindResponse Find(FindCriteria criteria)
        {
            string contractName      = criteria.ContractTypeNames[0].Name;
            string contractNamespace = criteria.ContractTypeNames[0].Namespace;

            FindResponse response = DiscoveryHelper.CreateFindResponse();

            ManualResetEvent handle = new ManualResetEvent(false);

            Action <Uri, Uri[]> addEndpoint = (address, scopes) =>
            {
                EndpointDiscoveryMetadata metadata = new EndpointDiscoveryMetadata();
                metadata.Address = new EndpointAddress(address);
                if (scopes != null)
                {
                    foreach (Uri scope in scopes)
                    {
                        metadata.Scopes.Add(scope);
                    }
                }
                response.Endpoints.Add(metadata);

                if (response.Endpoints.Count >= criteria.MaxResults)
                {
                    handle.Set();
                }
            };

            DiscoveryResponseCallback callback = new DiscoveryResponseCallback(contractName, contractNamespace, addEndpoint);

            ServiceHost host = new ServiceHost(callback);

            host.AddServiceEndpoint(typeof(IServiceBusDiscoveryCallback), Endpoint.Binding, ResponseAddress.AbsoluteUri);
            host.Description.Endpoints[0].Behaviors.Add(new ServiceRegistrySettings(DiscoveryType.Public));
            TransportClientEndpointBehavior credentials = Endpoint.Behaviors.Find <TransportClientEndpointBehavior>();

            Debug.Assert(credentials != null);

            host.Description.Endpoints[0].Behaviors.Add(credentials);

            host.Open();

            try
            {
                DiscoveryRequest(criteria.ContractTypeNames[0].Name, criteria.ContractTypeNames[0].Namespace, criteria.Scopes.ToArray(), ResponseAddress);

                bool found = handle.WaitOne(criteria.Duration);
                if (found == false)
                {
                    Trace.WriteLine("Could not find endpoints within specified discovery criteria duration");
                }
            }
            catch
            {}
            finally
            {
                try
                {
                    host.Abort();
                }
                catch (ProtocolException)
                {}
            }
            return(response);
        }
Example #52
0
 public void InvokeOneWay_waitOnEvent_received()
 {
     var address = @"net.pipe://127.0.0.1/1/test.test/test";
     var wait = new ManualResetEvent(false);
     var serv = new Service(wait);
     var host = new ServiceHost(serv, new Uri(address));
     var b = new NetNamedPipeBinding();
     host.AddServiceEndpoint(typeof(IService), b, address);
     var f = new ChannelFactory<IService>(b);
     var c = f.CreateChannel(new EndpointAddress(address));
     host.Open();
     c.DoOneWay();
     wait.WaitOne();
     host.Dispose();
 }
Example #53
0
 public void PipeChannel_openClose_fail()
 {
     var address = @"ipc:///test" + MethodBase.GetCurrentMethod().Name;
     var b = new LocalBinding();
     var serv = new Service(null);
     var host = new ServiceHost(serv, new Uri(address));
     host.AddServiceEndpoint(typeof(IService), b, address);
     host.Open();
     var f = new ChannelFactory<IService>(b);
     var c = f.CreateChannel(new EndpointAddress(address));
     c.DoWithParamsAndResult(null, Guid.Empty);
     host.Close();
     Exception comminicationEx = null;
     try
     {
         c.DoWithParamsAndResult(null, Guid.Empty);
     }
     catch (Exception ex)
     {
         comminicationEx = ex;
     }
     var obj = c as ICommunicationObject;
     var state = obj.State;
     Assert.AreEqual(CommunicationState.Faulted, state);
     Assert.That(comminicationEx, new ExceptionTypeConstraint(typeof(CommunicationException)));
 }
Example #54
0
        int Start(string strDataDir,
                  out string strError)
        {
            strError = "";

            CloseHosts();

            List <string> urls = StringUtil.SplitList(this.HostUrl, ';');

            ServiceHost host = new ServiceHost(typeof(LibraryService));

            this.m_hosts.Add(host);

            HostInfo info = new HostInfo();

            info.DataDir = strDataDir;
            host.Extensions.Add(info);

            bool bHasWsHttp = false;
            int  i          = 0;

            foreach (string strTempUrl in urls)
            {
                string strUrl = strTempUrl.Trim();

                if (string.IsNullOrEmpty(strUrl) == true)
                {
                    continue;
                }

                ///
                // 绑定协议

                Uri uri = null;
                try
                {
                    uri = new Uri(strUrl);
                }
                catch (Exception ex)
                {
                    strError = "dp2Library OnStart() 警告:发现不正确的协议URL '" + strUrl + "' (异常信息: " + ex.Message + ")。该URL已被放弃绑定。";
                    return(-1);
                }

                if (uri.Scheme.ToLower() == "net.pipe")
                {
                    host.AddServiceEndpoint(typeof(ILibraryService),
                                            CreateNamedpipeBinding0(),
                                            strUrl);
                }
                else if (uri.Scheme.ToLower() == "net.tcp")
                {
                    host.AddServiceEndpoint(typeof(ILibraryService),
                                            CreateNetTcpBinding0(),
                                            strUrl);
                }
                else if (uri.Scheme.ToLower() == "http")
                {
                    ServiceEndpoint endpoint = host.AddServiceEndpoint(typeof(ILibraryService),
                                                                       CreateWsHttpBinding1(),
                                                                       strUrl);
                    bHasWsHttp = true;
                }
                else if (uri.Scheme.ToLower() == "rest.http")
                {
                    ServiceEndpoint endpoint = host.AddServiceEndpoint(typeof(ILibraryServiceREST),
                                                                       CreateWebHttpBinding1(),
                                                                       strUrl.Substring(5)); // rest. 这几个字符要去掉
                    if (endpoint.Behaviors.Find <WebHttpBehavior>() == null)
                    {
                        WebHttpBehavior behavior = new WebHttpBehavior();
                        behavior.DefaultBodyStyle = System.ServiceModel.Web.WebMessageBodyStyle.Wrapped;
                        behavior.DefaultOutgoingResponseFormat   = System.ServiceModel.Web.WebMessageFormat.Json;
                        behavior.AutomaticFormatSelectionEnabled = true;
                        behavior.HelpEnabled = true;
                        endpoint.Behaviors.Add(behavior);
                    }
                }
                else
                {
                    // 警告不能支持的协议
                    strError = "dp2Library OnStart() 警告:发现不能支持的协议类型 '" + strUrl + "'";
                    return(-1);
                }

                info.Protocol = uri.Scheme.ToLower();

                // 只有第一个host才有metadata能力
                if (// i == 0 //
                    uri.Scheme.ToLower() == "http" &&
                    host.Description.Behaviors.Find <ServiceMetadataBehavior>() == null)
                {
                    string strMetadataUrl = strUrl;    //  "http://localhost:8001/dp2library/xe/";
                    if (strMetadataUrl[strMetadataUrl.Length - 1] != '/')
                    {
                        strMetadataUrl += "/";
                    }
                    strMetadataUrl += "metadata";

                    ServiceMetadataBehavior behavior = new ServiceMetadataBehavior();
                    behavior.HttpGetEnabled = true;
                    behavior.HttpGetUrl     = new Uri(strMetadataUrl);
                    host.Description.Behaviors.Add(behavior);

                    this.MetadataUrl = strMetadataUrl;
                }

                i++;
            }

            // 如果具有ws1/ws2 binding,才启用证书
            if (bHasWsHttp == true)
            {
                try
                {
                    string           strCertSN = "";
                    X509Certificate2 cert      = GetCertificate(strCertSN,
                                                                out strError);
                    if (cert == null)
                    {
                        strError = "dp2Library OnStart() 准备证书 时发生错误: " + strError;
                        return(-1);
                    }
                    else
                    {
                        host.Credentials.ServiceCertificate.Certificate = cert;
                    }
                }
                catch (Exception ex)
                {
                    strError = "dp2Library OnStart() 获取证书时发生错误: " + ExceptionUtil.GetExceptionMessage(ex);
                    return(-1);
                }
            }

            if (host.Description.Behaviors.Find <ServiceThrottlingBehavior>() == null)
            {
                ServiceThrottlingBehavior behavior = new ServiceThrottlingBehavior();
                behavior.MaxConcurrentCalls     = 50;
                behavior.MaxConcurrentInstances = 1000;
                behavior.MaxConcurrentSessions  = 1000;
                host.Description.Behaviors.Add(behavior);
            }

            // IncludeExceptionDetailInFaults
            ServiceDebugBehavior debug_behavior = host.Description.Behaviors.Find <ServiceDebugBehavior>();

            if (debug_behavior == null)
            {
                host.Description.Behaviors.Add(new ServiceDebugBehavior()
                {
                    IncludeExceptionDetailInFaults = true
                });
            }
            else
            {
                if (debug_behavior.IncludeExceptionDetailInFaults == false)
                {
                    debug_behavior.IncludeExceptionDetailInFaults = true;
                }
            }

            host.Opening += new EventHandler(host_Opening);
            host.Closing += new EventHandler(m_host_Closing);

            try
            {
                host.Open();
            }
            catch (Exception ex)
            {
                string strInstanceName = "";
                strError = "dp2Library OnStart() host.Open() 时发生错误: instancename=[" + strInstanceName + "]:" + ExceptionUtil.GetExceptionMessage(ex);
                return(-1);
            }

#if NO
            strError = "test error";
            return(-1);
#endif

            return(0);
        }
Example #55
0
        public void StartService()
        {
            string srvCertCN = Formatter.ParseName(WindowsIdentity.GetCurrent().Name);

            if (srvCertCN.ToLower() != "testservis")
            {
                throw new Exception("Nisi admir");
            }

            NetTcpBinding binding = new NetTcpBinding();

            binding.Security.Transport.ClientCredentialType = TcpClientCredentialType.Certificate;

            ServiceHost host = new ServiceHost(typeof(ReaderService));

            host.AddServiceEndpoint(typeof(IReaderService), binding, Config.ReaderServiceAddress);

            //--------------------------------------------------------------------------------
            host.Authorization.ServiceAuthorizationManager = new MyServiceAuthorizationManager();

            List <IAuthorizationPolicy> policies = new List <IAuthorizationPolicy>();

            policies.Add(new CustomAuthorizationPolicy());
            host.Authorization.ExternalAuthorizationPolicies = policies.AsReadOnly();
            //---------------------------------------------------------------------------------

            ///PeerTrust - for development purposes only to temporarily disable the mechanism that checks the chain of trust for a certificate.
            ///To do this, set the CertificateValidationMode property to PeerTrust (PeerOrChainTrust) - specifies that the certificate can be self-issued (peer trust)
            ///To support that, the certificates created for the client and server in the personal certificates folder need to be copied in the Trusted people -> Certificates folder.
            ///host.Credentials.ClientCertificate.Authentication.CertificateValidationMode = X509CertificateValidationMode.PeerTrust;

            ///Custom validation mode enables creation of a custom validator - CustomCertificateValidator
            host.Credentials.ClientCertificate.Authentication.CertificateValidationMode  = X509CertificateValidationMode.Custom;
            host.Credentials.ClientCertificate.Authentication.CustomCertificateValidator = new ServiceCertValidator();

            ///If CA doesn't have a CRL associated, WCF blocks every client because it cannot be validated
            host.Credentials.ClientCertificate.Authentication.RevocationMode = X509RevocationMode.NoCheck;

            ///Set appropriate service's certificate on the host. Use CertManager class to obtain the certificate based on the "srvCertCN"
            host.Credentials.ServiceCertificate.Certificate = CertManager.GetCertificateFromStorage(StoreName.My, StoreLocation.LocalMachine, srvCertCN);
            /// host.Credentials.ServiceCertificate.Certificate = CertManager.GetCertificateFromFile("WCFService.pfx");

            //--------------------------------------------------------------------
            ServiceDebugBehavior debug = host.Description.Behaviors.Find <ServiceDebugBehavior>();

            // if not found - add behavior with setting turned on
            if (debug == null)
            {
                host.Description.Behaviors.Add(
                    new ServiceDebugBehavior()
                {
                    IncludeExceptionDetailInFaults = true
                });
            }
            else
            {
                // make sure setting is turned ON
                if (!debug.IncludeExceptionDetailInFaults)
                {
                    debug.IncludeExceptionDetailInFaults = true;
                }
            }
            //---------------------------------------------------------------------

            if (host.Credentials.ServiceCertificate.Certificate == null)
            {
                Console.WriteLine("Certificate does not exist: CN=" + srvCertCN);
                Console.WriteLine(ServiceName + " stopped");
                host = null;
            }
            else
            {
                host.Open();
                Console.WriteLine(ServiceName + " service started.");
            }
        }
Example #56
0
        static void StartWCFService(Dictionary <Type, Type> serviceTypes, string servicePort)
        {
            servicePort = XML.Read(ConfigFile, "Service", "Port", servicePort);

            string endpointAddress = string.Empty;
            string tName           = string.Empty;

            foreach (var item in serviceTypes)
            {
                tName           = item.Key.Name.Substring(1);
                endpointAddress = string.Format("http://localhost:{0}/{1}", servicePort, tName);
                ServiceHost host = new ServiceHost(item.Value, new Uri(endpointAddress));

                CustomBinding customBinding = new CustomBinding("GZipHttpBinding");
                customBinding.ReceiveTimeout = new TimeSpan(1, 0, 0);
                host.AddServiceEndpoint(item.Key, customBinding, string.Empty);

                ServiceMetadataBehavior behavior = host.Description.Behaviors.Find <ServiceMetadataBehavior>();
                {
                    if (behavior == null)
                    {
                        behavior = new ServiceMetadataBehavior();
                        behavior.HttpGetEnabled = true;
                        host.Description.Behaviors.Add(behavior);
                    }
                    else
                    {
                        behavior.HttpGetEnabled = true;
                    }
                }

                {
                    System.ServiceModel.Description.DataContractSerializerOperationBehavior dataContractBehavior =
                        host.Description.Behaviors.Find <System.ServiceModel.Description.DataContractSerializerOperationBehavior>()
                        as System.ServiceModel.Description.DataContractSerializerOperationBehavior;
                    if (dataContractBehavior != null)
                    {
                        dataContractBehavior.MaxItemsInObjectGraph = int.MaxValue;
                    }
                }

                host.Opened += delegate
                {
                    Console.WriteLine("{0}已经启动,按任意键终止服务!", tName);
                };

                host.Open();
                serviceHosts.Add(host);
            }

            Console.Read();
            if (serviceHosts != null)
            {
                foreach (ServiceHost t in serviceHosts)
                {
                    if (t != null)
                    {
                        t.Close();
                    }
                }
            }
        }
        /// <summary>
        /// Setup service for given config
        /// </summary>
        /// <param name="contract">Contract type of the host</param>
        /// <param name="config">Config of component</param>
        public void Setup(Type contract, HostConfig config)
        {
            // Create base address depending on chosen binding
            string protocol;

            switch (config.BindingType)
            {
            case ServiceBindingType.NetTcp:
                protocol = "net.tcp";
                break;

            default:
                protocol = "http";
                break;
            }

            // Create service host
            _service           = _factory.CreateServiceHost(contract);
            _contract          = contract;
            _endpointAttribute = _contract.GetCustomAttribute <EndpointAttribute>();

            // Configure host
            _service.CloseTimeout = TimeSpan.Zero;

            // Set binding
            Binding binding;

            switch (config.BindingType)
            {
            case ServiceBindingType.BasicHttp: binding = BindingFactory.CreateBasicHttpBinding(config.RequiresAuthentification);
                break;

            case ServiceBindingType.NetTcp: binding = BindingFactory.CreateNetTcpBinding(config.RequiresAuthentification);
                break;

            default: binding = BindingFactory.CreateWebHttpBinding();
                break;
            }

            // Set default timeouts
            binding.OpenTimeout = _portConfig.OpenTimeout != PortConfig.InfiniteTimeout
                ? TimeSpan.FromSeconds(_portConfig.OpenTimeout)
                : TimeSpan.MaxValue;

            binding.CloseTimeout = _portConfig.CloseTimeout != PortConfig.InfiniteTimeout
                ? TimeSpan.FromSeconds(_portConfig.CloseTimeout)
                : TimeSpan.MaxValue;

            binding.SendTimeout = _portConfig.SendTimeout != PortConfig.InfiniteTimeout
                ? TimeSpan.FromSeconds(_portConfig.SendTimeout)
                : TimeSpan.MaxValue;

            binding.ReceiveTimeout = _portConfig.ReceiveTimeout != PortConfig.InfiniteTimeout
                ? TimeSpan.FromSeconds(_portConfig.ReceiveTimeout)
                : TimeSpan.MaxValue;

            // Create endpoint address from config
            var port = config.BindingType == ServiceBindingType.NetTcp ? _portConfig.NetTcpPort : _portConfig.HttpPort;

            // Override binding timeouts if necessary
            if (config is ExtendedHostConfig extendedConfig && extendedConfig.OverrideFrameworkConfig)
            {
                // Override binding timeouts if necessary
                port = extendedConfig.Port;
                binding.OpenTimeout = extendedConfig.OpenTimeout != PortConfig.InfiniteTimeout
                    ? TimeSpan.FromSeconds(extendedConfig.OpenTimeout)
                    : TimeSpan.MaxValue;

                binding.CloseTimeout = extendedConfig.CloseTimeout != PortConfig.InfiniteTimeout
                    ? TimeSpan.FromSeconds(extendedConfig.CloseTimeout)
                    : TimeSpan.MaxValue;

                binding.SendTimeout = extendedConfig.SendTimeout != PortConfig.InfiniteTimeout
                    ? TimeSpan.FromSeconds(extendedConfig.SendTimeout)
                    : TimeSpan.MaxValue;

                binding.ReceiveTimeout = extendedConfig.ReceiveTimeout != PortConfig.InfiniteTimeout
                    ? TimeSpan.FromSeconds(extendedConfig.ReceiveTimeout)
                    : TimeSpan.MaxValue;
            }

            _endpointAddress = $"{protocol}://{_portConfig.Host}:{port}/{config.Endpoint}/";

            var endpoint = _service.AddServiceEndpoint(contract, binding, _endpointAddress);

            // Add  behaviors
            endpoint.Behaviors.Add(new CultureBehavior());

            if (config.BindingType == ServiceBindingType.WebHttp)
            {
                endpoint.Behaviors.Add(new WebHttpBehavior());
                endpoint.Behaviors.Add(new CorsBehaviorAttribute());
            }

            if (config.MetadataEnabled)
            {
                var serviceMetadataBehavior = new ServiceMetadataBehavior
                {
                    HttpGetEnabled = true,
                    HttpGetUrl     = new Uri($"http://{_portConfig.Host}:{_portConfig.HttpPort}/Metadata/{config.Endpoint}")
                };
                _service.Description.Behaviors.Add(serviceMetadataBehavior);
            }

            if (config.HelpEnabled)
            {
                var serviceDebugBehavior = _service.Description.Behaviors.Find <ServiceDebugBehavior>();
                serviceDebugBehavior.IncludeExceptionDetailInFaults = true;
                serviceDebugBehavior.HttpHelpPageEnabled            = true;
                serviceDebugBehavior.HttpHelpPageUrl = new Uri($"http://{_portConfig.Host}:{_portConfig.HttpPort}/Help/{config.Endpoint}");
            }

            _hostConfig = config;
        }
        static void Main(string[] args)
        {
            ServiceHost    hostCalculatorManager = null;
            WebServiceHost hostImageDownloader   = null;

            try
            {
                hostCalculatorManager = new ServiceHost(typeof(RelayCalculatorManager));
                hostImageDownloader   = new WebServiceHost(typeof(ImageManager));

                ServiceBusEnvironment.SystemConnectivity.Mode = ConnectivityMode.AutoDetect;

                #region Endpoint configuration - CalculatorManager

                hostCalculatorManager.AddServiceEndpoint(
                    typeof(IRelayCalculatorService),
                    new NetTcpRelayBinding(),
                    ServiceBusEnvironment
                    .CreateServiceUri("sb", Common.AccessData.ServiceBusNamespace, "RelayCalculatorService"))
                .Behaviors.Add(new TransportClientEndpointBehavior
                {
                    TokenProvider = TokenProvider.CreateSharedAccessSignatureTokenProvider(
                        Common.AccessData.SasTestKeyName,
                        Common.AccessData.SasTestKeyValue)
                });

                #endregion

                #region Endpoint configuration - ImageManager

                var sasCredential = new TransportClientEndpointBehavior
                {
                    TokenProvider =
                        TokenProvider.CreateSharedAccessSignatureTokenProvider(
                            Common.AccessData.SasTestKeyName,
                            Common.AccessData.SasTestKeyValue)
                };

                hostImageDownloader.AddServiceEndpoint(
                    typeof(IImageService),
                    new WebHttpRelayBinding(
                        EndToEndWebHttpSecurityMode.Transport,
                        RelayClientAuthenticationType.None),
                    ServiceBusEnvironment.CreateServiceUri(
                        "https", Common.AccessData.ServiceBusNamespace, "ImageService"));

                foreach (var endpoint in hostImageDownloader.Description.Endpoints)
                {
                    endpoint.Behaviors.Add(sasCredential);
                }

                #endregion

                Console.WriteLine("1) Start hosting the service(s)");
                Console.WriteLine();
                Console.WriteLine("......................................................");

                StartHostingService(hostCalculatorManager, false);
                StartHostingService(hostImageDownloader, true);

                Console.WriteLine();
                Console.WriteLine("2) press <enter> to exit...");
                Console.ReadKey();

                hostCalculatorManager.Close();
                hostImageDownloader.Close();
            }
            catch (Exception ex)
            {
                Debugger.Break();

                Abort(hostCalculatorManager);
                Abort(hostImageDownloader);

                throw;
            }
        }
Example #59
0
        // 打开指定的 host
        // parameters:
        //      instance_names  要打开的实例的名字,数组。如果 == null,表示全部打开
        public int OpenHosts(List <string> instance_names,
                             out List <string> errors)
        {
            // CloseHosts();

            string strError = "";

            errors = new List <string>();
            int nCount = 0;


            // 检查不同实例的 dp2kernel 中所用的 SQL 数据库名是否发生了重复和冲突
            // return:
            //      -1  检查过程出错
            //      0   没有冲突
            //      1   发生了冲突。报错信息在 strError 中
            int nRet = CheckSqlDbNames(out strError);

            if (nRet != 0)
            {
                strError = "dp2Kernel 实例启动阶段发生严重错误: " + strError;
                errors.Add(strError);
                this.Log.WriteEntry(strError, EventLogEntryType.Error);
                return(0);
            }

            for (int i = 0; ; i++)
            {
                string   strInstanceName = "";
                string   strDataDir      = "";
                string   strCertSN       = "";
                string[] existing_urls   = null;
                bool     bRet            = GetInstanceInfo("dp2Kernel",
                                                           i,
                                                           out strInstanceName,
                                                           out strDataDir,
                                                           out existing_urls,
                                                           out strCertSN);
                if (bRet == false)
                {
                    break;
                }

                if (instance_names != null && instance_names.IndexOf(strInstanceName) == -1)
                {
                    continue;
                }

                // 查重,看看 host 是否已经存在
                if (FindHost(strInstanceName) != null)
                {
                    errors.Add("实例 '" + strInstanceName + "' 调用前已经是启动状态,不能重复启动");
                    continue;
                }
#if NO
                string strWsHostUrl = FindUrl("http", existing_urls);

                string strNamedpipeHostUrl = FindUrl("net.pipe", existing_urls);
                string strNetTcpHostUrl    = FindUrl("net.tcp", existing_urls);
#endif

                ServiceHost host = new ServiceHost(typeof(KernelService));
                this.m_hosts.Add(host);

                nCount++;

                HostInfo info = new HostInfo();
                info.DataDir      = strDataDir;
                info.InstanceName = strInstanceName;
                host.Extensions.Add(info);
                ///

                bool bHasWsHttp = false;
                // 绑定协议
                foreach (string url in existing_urls)
                {
                    if (string.IsNullOrEmpty(url) == true)
                    {
                        continue;
                    }

                    Uri uri = null;
                    try
                    {
                        uri = new Uri(url);
                    }
                    catch (Exception ex)
                    {
                        strError = "dp2Kernel OnStart() 警告:发现不正确的协议URL '" + url + "' (异常信息: " + ex.Message + ")。该URL已被放弃绑定。";
                        this.Log.WriteEntry(strError,
                                            EventLogEntryType.Error);
                        errors.Add(strError);
                        continue;
                    }

                    if (uri.Scheme.ToLower() == "http")
                    {
                        host.AddServiceEndpoint(typeof(IKernelService),
                                                CreateWsHttpBinding1(),
                                                url);
                        bHasWsHttp = true;
                    }
                    else if (uri.Scheme.ToLower() == "net.pipe")
                    {
                        host.AddServiceEndpoint(typeof(IKernelService),
                                                CreateNamedpipeBinding0(),
                                                url);
                    }
                    else if (uri.Scheme.ToLower() == "net.tcp")
                    {
                        host.AddServiceEndpoint(typeof(IKernelService),
                                                CreateNetTcpBinding0(),
                                                url);
                    }
                    else
                    {
                        // 警告不能支持的协议
                        strError = "dp2Kernel OnStart() 警告:发现不能支持的协议类型 '" + url + "'";
                        this.Log.WriteEntry(strError,
                                            EventLogEntryType.Information);
                        errors.Add(strError);
                    }
                }

                // 如果具有ws1/ws2 binding,才启用证书
                if (bHasWsHttp == true /*String.IsNullOrEmpty(strWsHostUrl) == false*/)
                {
                    try
                    {
                        // host.Credentials.ServiceCertificate.Certificate = GetCertificate(strCertSN);
                        X509Certificate2 cert = GetCertificate(strCertSN,
                                                               out strError);
                        if (cert == null)
                        {
                            strError = "dp2Kernel OnStart() 准备证书 时发生错误: " + strError;
                            this.Log.WriteEntry(strError,
                                                EventLogEntryType.Error);
                            errors.Add(strError);
                        }
                        else
                        {
                            host.Credentials.ServiceCertificate.Certificate = cert;
                        }
                    }
                    catch (Exception ex)
                    {
                        strError = "dp2Kernel OnStart() 获取证书时发生错误: " + ex.Message;
                        this.Log.WriteEntry(strError,
                                            EventLogEntryType.Error);
                        errors.Add(strError);
                        return(nCount);
                    }
                }

                // 只有第一个host才有metadata能力
                if (// i == 0
                    m_hosts.Count == 1 &&
                    host.Description.Behaviors.Find <ServiceMetadataBehavior>() == null)
                {
                    string strWsHostUrl = FindUrl("http", existing_urls);

                    string strMetadataUrl = strWsHostUrl;
                    if (String.IsNullOrEmpty(strMetadataUrl) == true)
                    {
                        strMetadataUrl = "http://localhost:8001/dp2kernel/";
                    }
                    if (strMetadataUrl[strMetadataUrl.Length - 1] != '/')
                    {
                        strMetadataUrl += "/";
                    }
                    strMetadataUrl += "metadata";

                    ServiceMetadataBehavior behavior = new ServiceMetadataBehavior();
                    behavior.HttpGetEnabled = true;
                    behavior.HttpGetUrl     = new Uri(strMetadataUrl);
                    host.Description.Behaviors.Add(behavior);
                }

                if (host.Description.Behaviors.Find <ServiceThrottlingBehavior>() == null)
                {
                    ServiceThrottlingBehavior behavior = new ServiceThrottlingBehavior();
                    behavior.MaxConcurrentCalls     = 50;
                    behavior.MaxConcurrentInstances = 1000;
                    behavior.MaxConcurrentSessions  = 1000;
                    host.Description.Behaviors.Add(behavior);
                }

                // IncludeExceptionDetailInFaults
                ServiceDebugBehavior debug_behavior = host.Description.Behaviors.Find <ServiceDebugBehavior>();
                if (debug_behavior == null)
                {
                    host.Description.Behaviors.Add(new ServiceDebugBehavior()
                    {
                        IncludeExceptionDetailInFaults = true
                    });
                }
                else
                {
                    if (debug_behavior.IncludeExceptionDetailInFaults == false)
                    {
                        debug_behavior.IncludeExceptionDetailInFaults = true;
                    }
                }

                host.Opening += new EventHandler(host_Opening);
                host.Closing += new EventHandler(m_host_Closing);

                try
                {
                    host.Open();
                }
                catch (Exception ex)
                {
                    // 让调试器能感觉到
                    if (this.m_bConsoleRun == true)
                    {
                        throw ex;
                    }

                    strError = "dp2Kernel OnStart() host.Open() 时发生错误: instancename=[" + strInstanceName + "]:" + ex.Message;
                    this.Log.WriteEntry(strError,
                                        EventLogEntryType.Error);
                    errors.Add(strError);
                    return(nCount);
                }
            }

            return(nCount);
        }
Example #60
0
 public static void Start()
 {
     _host = new ServiceHost(Service, ServiceUri);
     _host.AddServiceEndpoint(typeof(ICommandService), new NetNamedPipeBinding(), PipeName);
     _host.Open();
 }