static void Main(string[] args)
        {
            Uri baseAddress = new Uri("http://localhost:6525/SchoolService");

            using (var host = new System.ServiceModel.ServiceHost(typeof(School.Infrastructure.ServiceSchool), baseAddress))
            {
                ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
                smb.HttpGetEnabled = true;
                smb.MetadataExporter.PolicyVersion = PolicyVersion.Policy15;

                host.Description.Behaviors.Remove<ServiceDebugBehavior>();
                ServiceDebugBehavior sdb = new ServiceDebugBehavior();
                sdb.IncludeExceptionDetailInFaults = true;

                host.Description.Behaviors.Add(smb);
                host.Description.Behaviors.Add(sdb);

                host.Open();

                Console.WriteLine("The service is ready at: {0}", baseAddress);
                Console.WriteLine("Press <Enter> to stop the service");
                Console.ReadKey();
                host.Close();

            }
        }
Exemple #2
0
        static void Main(string[] args)
        {
            Uri baseAddress = new Uri("http://localhost:8080/MaquinaInequacoesSelfHost");

            using (ServiceHost host = new ServiceHost(typeof(MaquinaInequacoesService), baseAddress))
            {
                ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
                smb.HttpGetEnabled = true;
                //smb.MetadataExporter.PolicyVersion = PlicyVersion
                host.Description.Behaviors.Add(smb);

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

                }

                host.Open();

                Console.WriteLine("Serviço ativo em: " + baseAddress);
                Console.WriteLine("[Enter] para parar");
                Console.ReadLine();

                host.Close();
            }
        }
Exemple #3
0
        public void CreateHost(Uri address, object instance, Type interfaceType)
        {
            this.host = new ServiceHost(instance, address);
            this.host.Faulted += new EventHandler(host_Faulted);
            Binding httpBinding = ConfigurationFactory.CreateDualBinding();
            this.host.AddServiceEndpoint(interfaceType, httpBinding, address);

            //ServiceMetadataBehavior metadataBehavior = host.Description.Behaviors.Find<ServiceMetadataBehavior>();
            //if (metadataBehavior == null)
            //{
            //    metadataBehavior = new ServiceMetadataBehavior();
            //    metadataBehavior.HttpGetEnabled = true;
            //    metadataBehavior.HttpGetUrl = new Uri(address + "mex/");
            //    host.Description.Behaviors.Add(metadataBehavior);
            //}
            //else
            //{
            //    metadataBehavior.HttpGetEnabled = true;
            //    metadataBehavior.HttpGetUrl = new Uri(address + "mex/");
            //}
            var debugBehavior = host.Description.Behaviors.Find<ServiceDebugBehavior>();
            if (debugBehavior == null)
            {

                debugBehavior = new ServiceDebugBehavior {IncludeExceptionDetailInFaults = true};
                host.Description.Behaviors.Add(debugBehavior);
            }
            else
            {
                debugBehavior.IncludeExceptionDetailInFaults = true;
            }

            //host.AddServiceEndpoint(typeof(IMetadataExchange), httpBinding, new Uri(address + "mex/"));
        }
Exemple #4
0
      public static void Open(string tibcoEndpointUri) {
         Uri uri;
         if (!Uri.TryCreate(tibcoEndpointUri, UriKind.Absolute, out uri)) {
            uri = new Uri("http://0.0.0.0:50701");
         }
         _host = new ServiceHost(typeof(OscarServices), uri);
         var smb = new ServiceMetadataBehavior { 
            HttpGetEnabled = true,
         };
         smb.MetadataExporter.PolicyVersion = PolicyVersion.Policy15;
         _host.Description.Behaviors.Add(smb);

         var sdb = _host.Description.Behaviors.Find<ServiceDebugBehavior>();
         if (sdb == null) {
            sdb = new ServiceDebugBehavior();
            _host.Description.Behaviors.Add(sdb);
         }
         sdb.IncludeExceptionDetailInFaults = false;
         sdb.HttpHelpPageEnabled = false;
         

         _host.AddServiceEndpoint(ServiceMetadataBehavior.MexContractName, MetadataExchangeBindings.CreateMexHttpBinding(), "mex");
         var bhb = new BasicHttpBinding() { Namespace = "urn:Mpcr.Services.Oscar" };
         bhb.Security.Mode = BasicHttpSecurityMode.TransportCredentialOnly;
         bhb.Security.Transport.ClientCredentialType = HttpClientCredentialType.Ntlm;
         _host.AddServiceEndpoint(typeof(IOscarServices), bhb, "");
         _host.Authorization.ServiceAuthorizationManager = new TibcoAuthManager();
         _host.Open();
      }
        public BaseBootstrapper(bool isHttpEnabled = false)
        {
            this.container.AddFacility<TypedFactoryFacility>().AddFacility<WcfFacility>(f => f.CloseTimeout = TimeSpan.Zero);

            ServiceMetadataBehavior metadata = new ServiceMetadataBehavior();

            if (isHttpEnabled)
            {
                metadata.HttpGetEnabled = true;
                metadata.HttpsGetEnabled = true;
            }

            ServiceDebugBehavior returnFaults = new ServiceDebugBehavior() { IncludeExceptionDetailInFaults = true };

            this.container.Register(
                Component.For<IServiceBehavior>().Instance(metadata),
                Component.For<IServiceBehavior>().Instance(returnFaults));

            this.container.Install(FromAssembly.InDirectory(new AssemblyFilter(ConfigurationManager.AppSettings["ExtensionFolder"] ?? string.Empty)));

            this.kernel = this.container.Kernel;

            container.Register(Component.For<IJsonSerializer>().ImplementedBy<JsonSerializer>().Named("GeneralJsonSerializer").LifeStyle.PerWcfOperation());

            CheckCastleRegisterComponent();
        }
        private void Start(string baseAddress, string path)
        {
            ModuleProc PROC = new ModuleProc(this.DYN_MODULE_NAME, "Start");

            try
            {
                if (_host == null)
                {
                    lock (_lock)
                    {
                        if (_host == null)
                        {
                            // Binding
                            NetTcpBinding binding = AppNotifyServiceHelper.CreateBinding();

                            // Host
                            Uri uriTcp = new Uri(new Uri(Uri.UriSchemeNetTcp + "://" + baseAddress), path);
                            //Uri uriHttp = new Uri(new Uri(Uri.UriSchemeHttp + "://" + baseAddress), path);
                            _host = new WcfServiceHost(typeof(AppNotifyService), _knownTypes, new Uri[] { uriTcp });

                            // ServiceMetadataBehavior
                            ServiceMetadataBehavior bServiceMetadata = _host.Description.Behaviors.Find<ServiceMetadataBehavior>();
                            if (bServiceMetadata == null)
                            {
                                bServiceMetadata = new ServiceMetadataBehavior();
                                _host.Description.Behaviors.Add(bServiceMetadata);
                            }
                            bServiceMetadata.HttpGetEnabled = false;
                            //bServiceMetadata.HttpGetUrl = uriHttp;                            

                            // ServiceDebugBehavior
                            ServiceDebugBehavior bServiceDebug = _host.Description.Behaviors.Find<ServiceDebugBehavior>();
                            if (bServiceDebug == null)
                            {
                                bServiceDebug = new ServiceDebugBehavior();
                                _host.Description.Behaviors.Add(bServiceDebug);
                            }
                            bServiceDebug.IncludeExceptionDetailInFaults = false;

                            // service points
                            _host.AddServiceEndpoint(typeof(IAppNotifyService), binding, string.Empty);
                            _host.AddServiceEndpoint(typeof(IMetadataExchange), MetadataExchangeBindings.CreateMexTcpBinding(), "mex");
                        }
                    }
                }

                if (_host != null &&
                    _host.State == CommunicationState.Created)
                {
                    _host.Open();
                    Log.InfoV(PROC, "Service started at : {0}", _host.BaseAddresses[0]);
                    _mreShutdown.Reset();
                }
            }
            catch (Exception ex)
            {
                Log.Exception(PROC, ex);
            }
        }
Exemple #7
0
        /// <summary>
        /// Load Configuration and Services
        /// </summary>
        public void LoadConfigAndService()
        {
            try
            {
                rtbOutput.AppendText(Environment.NewLine);

                //var dbLink = GetDefaultDatabase();

                //rtbOutput.AppendText(string.Format("Base de Datos: {0}", Environment.NewLine));
                //rtbOutput.AppendText(dbLink.Key);

                //using (var connection = GetConnection(dbLink.Value, dbLink.Key))
                //    rtbOutput.AppendText(string.Format("- (OK) {0}", Environment.NewLine));

                //rtbOutput.AppendText(Environment.NewLine);

                HostSevices = new Dictionary<string, ServiceHost>();

                rtbOutput.AppendText("Servicios: ");
                rtbOutput.AppendText(Environment.NewLine);

                // Matricular los servicios
                HostSevices.Add("Authentication.svc", new ServiceHost(typeof(DITO.Zenso.Services.Writes.Authentication)));
                HostSevices.Add("ZensoAdministration.svc", new ServiceHost(typeof(DITO.Zenso.Services.Writes.ZensoAdministration)));

                foreach (KeyValuePair<string, ServiceHost> host in HostSevices)
                {
                    // Iniciar los servicios
                    host.Value.Open();
                    rtbOutput.AppendText(string.Format("{0}{1}", String.Format("{0} Online.", host.Key), Environment.NewLine));

                    // Asignar comportamiento de debug
                    debugBehavior = host.Value.Description.Behaviors.Find<ServiceDebugBehavior>();

                    if (debugBehavior == null)
                    {
                        debugBehavior = new ServiceDebugBehavior
                        {
                            HttpHelpPageEnabled = false,
                            HttpHelpPageUrl = new Uri("http://www.dito.com.co"),
                            IncludeExceptionDetailInFaults = true
                        };

                        host.Value.Description.Behaviors.Add(debugBehavior);
                    }
                }
            }
            catch (Exception ex)
            {
                rtbOutput.AppendText(string.Format("Error: {0}{1}", ex.GetType(), Environment.NewLine));
                rtbOutput.AppendText(string.Format("Mensaje: {0}{1}", ex.Message, Environment.NewLine));

                this.WindowState = FormWindowState.Minimized;
                this.Show();
                this.WindowState = FormWindowState.Normal;
            }
        }
 public virtual IEnumerable<IServiceBehavior> GetBehaviors()
 {
     var serviceMetadataBehavior = new ServiceMetadataBehavior
                                       {
                                           HttpGetEnabled = true,
                                           MetadataExporter = { PolicyVersion = PolicyVersion.Policy15 }
                                       };
     var serviceDebugBehavior = new ServiceDebugBehavior { IncludeExceptionDetailInFaults = true };
     return new IServiceBehavior[] { serviceMetadataBehavior, serviceDebugBehavior };
 }
        private void ModifyBehaviors(ServiceDescription desc)
        {
            ServiceDebugBehavior debug = desc.Behaviors.Find<ServiceDebugBehavior>();
            if (debug == null)
            {
                debug = new ServiceDebugBehavior();
                desc.Behaviors.Add(debug);
            }

            debug.IncludeExceptionDetailInFaults = true;
        }
Exemple #10
0
        private static void UpdateServiceDebugBevhavior(ServiceDebugBehavior debug, ServiceHost host)
        {
            if (!host.Description.Behaviors.Contains(typeof(ServiceDebugBehavior)))
            {
                host.Description.Behaviors.Add(debug);

            }
            else
            {
                var db = (ServiceDebugBehavior) host.Description.Behaviors[typeof(ServiceDebugBehavior)];
                db.IncludeExceptionDetailInFaults = true;
            }
        }
Exemple #11
0
        void IServiceBehavior.AddBindingParameters(ServiceDescription description, ServiceHostBase serviceHostBase, Collection <ServiceEndpoint> endpoints, BindingParameterCollection parameters)
        {
            if (parameters == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("parameters");
            }

            ServiceDebugBehavior param = parameters.Find <ServiceDebugBehavior>();

            if (param == null)
            {
                parameters.Add(this);
            }
        }
        public void Intialize()
        {
            this.container = new WindsorContainer();

            ServiceDebugBehavior returnFaults = new ServiceDebugBehavior
            {
                IncludeExceptionDetailInFaults = true,
                HttpHelpPageEnabled = true
            };
            container.Register(
                Component.For<IServiceBehavior>().Instance(returnFaults)
            );

            container.Install(FromAssembly.This());
        }
        public static void ConfigureContainer(IWindsorContainer container)
        {
            var returnFaults = new ServiceDebugBehavior {IncludeExceptionDetailInFaults = true};

            container.AddFacility<WcfFacility>(f => 
            {
                f.Services.AspNetCompatibility = AspNetCompatibilityRequirementsMode.Required;
            })
                .Register(
                    Component.For<IServiceHostBuilder<XmlRpcServiceModel>>().ImplementedBy<XmlRpcServiceHostBuilder>(),
                    Component.For<XmlRpcServiceModel>(),
                    Component.For<IServiceBehavior>().Instance(returnFaults),
                    Component.For<IMetaWeblog>().ImplementedBy<MetaWeblogWcf>().Named("metaWebLog").LifeStyle.Transient
                    );

        }
        protected override void ApplyConfiguration()
        {
            base.ApplyConfiguration();

            // Our custom configuration code

            ServiceDebugBehavior sdb = this.Description.Behaviors.Find<ServiceDebugBehavior>();
            if (sdb == null)
            {
                sdb = new ServiceDebugBehavior();
                this.Description.Behaviors.Add(sdb);
            }

            // Ensure exception detail is included in response
            sdb.IncludeExceptionDetailInFaults = true;
        }
        public void Start()
        {
            this._UniqueId = _serviceConfig.UniqueId;
            string httpEndPstr = @"http://{0}:{1}/WcfPortal".FormatWith(_serviceConfig.HostAddress, _serviceConfig.HostPort);
            Uri httpUri = new Uri(httpEndPstr);

            _serviceHost = new ServiceHost(typeof(SAF.EntityFramework.Server.Hosts.WcfPortal), httpUri);

            Type t = _serviceHost.GetType();
            object obj = t.Assembly.CreateInstance("System.ServiceModel.Dispatcher.DataContractSerializerServiceBehavior", true,
                BindingFlags.CreateInstance | BindingFlags.Instance | BindingFlags.NonPublic, null,
                new object[] { false, Int32.MaxValue }, null, null);
            IServiceBehavior myServiceBehavior = obj as IServiceBehavior;

            if (myServiceBehavior != null)
            {
                _serviceHost.Description.Behaviors.Add(myServiceBehavior);
            }

            if (_serviceHost.Description.Behaviors.Find<ServiceMetadataBehavior>() == null)
            {
                var behavior = new ServiceMetadataBehavior();
                //交换方式
                behavior.HttpGetEnabled = true;
                //元数据交换地址
                behavior.HttpGetUrl = httpUri;
                //将行为添加到宿主上
                _serviceHost.Description.Behaviors.Add(behavior);
            }

            if (_serviceHost.Description.Behaviors.Find<ServiceDebugBehavior>() == null)
            {
                var behavior = new ServiceDebugBehavior();
                //交换方式
                behavior.IncludeExceptionDetailInFaults = true;
                //将行为添加到宿主上
                _serviceHost.Description.Behaviors.Add(behavior);
            }

            _serviceHost.AddServiceEndpoint(typeof(SAF.EntityFramework.Server.Hosts.IWcfPortal), new WSHttpBinding(SecurityMode.None), "");

            _serviceHost.AddServiceEndpoint(ServiceMetadataBehavior.MexContractName, MetadataExchangeBindings.CreateMexHttpBinding(), "mex");

            _thread = new Thread(RunService);
            _thread.IsBackground = true;
            _thread.Start();
        }
        private static void AddDebugBehavior(ServiceHostBase host)
        {
            var serviceDebugBehavior = host.Description.Behaviors.Find<ServiceDebugBehavior>();

            if (serviceDebugBehavior == null)
            {
                serviceDebugBehavior = new ServiceDebugBehavior
                {
                    IncludeExceptionDetailInFaults = true
                };
                host.Description.Behaviors.Add(serviceDebugBehavior);
            }
            else
            {
                serviceDebugBehavior.IncludeExceptionDetailInFaults = true;
            }
        }
 protected internal override object CreateBehavior()
 {
     ServiceDebugBehavior behavior = new ServiceDebugBehavior {
         HttpHelpPageEnabled = this.HttpHelpPageEnabled,
         HttpHelpPageUrl = this.HttpHelpPageUrl,
         HttpsHelpPageEnabled = this.HttpsHelpPageEnabled,
         HttpsHelpPageUrl = this.HttpsHelpPageUrl,
         IncludeExceptionDetailInFaults = this.IncludeExceptionDetailInFaults
     };
     if (!string.IsNullOrEmpty(this.HttpHelpPageBinding))
     {
         behavior.HttpHelpPageBinding = ConfigLoader.LookupBinding(this.HttpHelpPageBinding, this.HttpHelpPageBindingConfiguration);
     }
     if (!string.IsNullOrEmpty(this.HttpsHelpPageBinding))
     {
         behavior.HttpsHelpPageBinding = ConfigLoader.LookupBinding(this.HttpsHelpPageBinding, this.HttpsHelpPageBindingConfiguration);
     }
     return behavior;
 }
Exemple #18
0
        static void Main(string[] args)
        {
            ServiceHost host = new ServiceHost(typeof(GeoManager),
                new Uri("net.tcp://localhost:11011"),
                new Uri("http://localhost:11010"));

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

            ServiceThrottlingBehavior behaviorThrottling = host.Description.Behaviors.Find<ServiceThrottlingBehavior>();
            if(behaviorThrottling==null)
            {
                behaviorThrottling = new ServiceThrottlingBehavior();
                behaviorThrottling.MaxConcurrentSessions = 100;
                behaviorThrottling.MaxConcurrentCalls = 16;
                behaviorThrottling.MaxConcurrentInstances = 116;
                host.Description.Behaviors.Add(behaviorThrottling);
            }

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

            host.AddServiceEndpoint(typeof(IMetadataExchange), MetadataExchangeBindings.CreateMexTcpBinding(), "MEXTcp");
            host.AddServiceEndpoint(typeof(IMetadataExchange), MetadataExchangeBindings.CreateMexHttpBinding(), "MEXHttp");
            host.Open();

            Se
            Console.WriteLine("Press key to stop the service");
            Console.ReadKey();

            host.Close();
        }
Exemple #19
0
        static void Main(string[] args)
        {
            var baseAddress = new Uri("http://localhost:8733/server/subscriber/");
            using (var host = new ServiceHost(typeof(TimedConcurrentQueueSubscriber), baseAddress))
            {
                var serviceMetaDataBehavior = new ServiceMetadataBehavior
                {
                    HttpGetEnabled = true,
                    HttpsGetEnabled = true
                };
                host.Description.Behaviors.Add(serviceMetaDataBehavior);

                var serviceDebugBehavior = new ServiceDebugBehavior
                {
                    IncludeExceptionDetailInFaults = true
                };
                if (host.Description.Behaviors.Find<ServiceDebugBehavior>() == null)
                    host.Description.Behaviors.Add(serviceDebugBehavior);

                var duplexBinding = new WSDualHttpBinding
                {
                    ClientBaseAddress = new Uri("http://localhost:8734/client/dispatcher"),
                    MaxBufferPoolSize = 5242880,
                    MaxReceivedMessageSize = 6553600
                };
                var serviceEndpoint = new ServiceEndpoint(
                    ContractDescription.GetContract(typeof(Subscriber)),
                    duplexBinding, new EndpointAddress(baseAddress));
                host.Description.Endpoints.Add(serviceEndpoint);

                host.Open();

                Console.WriteLine($"{nameof(Subscriber)} service listening on {baseAddress}");
                Console.WriteLine("Press any key to exit....");
                Console.ReadKey(true);

                host.Close();
            }
        }
Exemple #20
0
		protected void Application_Start(object sender, EventArgs e)
		{
			ServiceDebugBehavior returnFaults = new ServiceDebugBehavior();
			returnFaults.IncludeExceptionDetailInFaults = true;
			returnFaults.HttpHelpPageEnabled = true;

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

			container = new WindsorContainer()
				.AddFacility<WcfFacility>()
				.Install(Configuration.FromXmlFile("windsor.xml"))
				.Register(
					Component.For<IServiceBehavior>().Instance(returnFaults),
					Component.For<IServiceBehavior>().Instance(metadata),
					Component.For<IAmUsingWindsor>()
					.Named("look no config")
					.ImplementedBy<UsingWindsorWithoutConfig>()
					.DependsOn(
						Property.ForKey("number").Eq(42))
					);
		}
Exemple #21
0
        static void Main(string[] args)
        {
            ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
            smb.HttpGetEnabled = true;

            ServiceDebugBehavior debug = new ServiceDebugBehavior();
            debug.IncludeExceptionDetailInFaults = true;

            //Create a URI to serve as the base address
            Uri httpUrl = new Uri("http://localhost:8090/InkDemo/InkDemoService");
            //Create ServiceHost
            ServiceHost host = new ServiceHost(typeof(InkDemoService), httpUrl);
            //host.AddServiceEndpoint(typeof(IInkDemoService), new WSHttpBinding(), "");
            //host.Description.Behaviors.Add(smb);
            //UpdateServiceDebugBevhavior(debug, host);
            //host.AddServiceEndpoint(typeof(IMetadataExchange), MetadataExchangeBindings.CreateMexHttpBinding(), "mex");
            host.Open();

            //Create a URI to serve as the base address
            Uri httpDualUrl = new Uri("http://localhost:8090/InkDemo/InkDemoDualService");
            //Create ServiceHost
            ServiceHost hostDual = new ServiceHost(typeof(InkDemoDualService), httpDualUrl);
            hostDual.AddServiceEndpoint(typeof(IInkDemoDualService), new WSDualHttpBinding(), "");
            hostDual.Description.Behaviors.Add(smb);
            UpdateServiceDebugBevhavior(debug, hostDual);

            foreach (var b in hostDual.Description.Behaviors)
            {
                Console.WriteLine(b);
            }

            hostDual.AddServiceEndpoint(typeof(IMetadataExchange), MetadataExchangeBindings.CreateMexHttpBinding(), "mex");
            hostDual.Open();

            Console.WriteLine("Service is host at " + DateTime.Now.ToString());
            Console.WriteLine("Host is running... Press <Enter> key to stop");
            Console.ReadLine();
        }
Exemple #22
0
        static void Main(string[] args)
        {
            string hostURI = "http://127.0.0.1:9001/BlogService";
            ServiceHost svcHost = null;
            try
            {
                Uri baseAddress = new Uri(hostURI);
                svcHost = new ServiceHost(typeof(BlogService.Lib.BlogService), baseAddress);
                ServiceMetadataBehavior servBehavior = new ServiceMetadataBehavior();
                ServiceDebugBehavior servDebugBehavior = new ServiceDebugBehavior();
                servBehavior.HttpGetEnabled = true;
                servDebugBehavior.IncludeExceptionDetailInFaults = true;

                svcHost.Description.Behaviors.Add(servBehavior);
                svcHost.Description.Behaviors.Find<ServiceDebugBehavior>().IncludeExceptionDetailInFaults = true;

                svcHost.Open();

                Console.WriteLine("\n\nBlog Service is Running  at following address");
                Console.WriteLine(baseAddress);

            }
            catch (Exception ex)
            {
                svcHost = null;
                Console.WriteLine("Blog Service can not be started \n\nError Message [" + ex.Message + "]");
            }

            if (svcHost != null)
            {
                Console.WriteLine("\nPress any key to close the Service");
                Console.ReadKey();
                svcHost.Close();
                svcHost = null;
            }

            Console.ReadKey();
        }
        protected void Application_Start(object sender, EventArgs e)
        {
            container = new WindsorContainer();

            var returnFaults = new ServiceDebugBehavior
            {
                IncludeExceptionDetailInFaults = true,
                HttpHelpPageEnabled = true
            };
            var metadata = new ServiceMetadataBehavior { HttpGetEnabled = true };

            container.Register(
                Component.For<IServiceBehavior>().Instance(returnFaults),
                Component.For<IServiceBehavior>().Instance(metadata));

            container
                .AddFacility<WcfFacility>()
                .Register(
                    Component
                        .For<IUploadService>()
                        .ImplementedBy<UploadService>()
                        .Named(typeof(IUploadService).Name)
                        .LifeStyle.Is(LifestyleType.Singleton)
                        .AsWcfService(new DefaultServiceModel()
                        .Hosted()
                        .AddEndpoints(WcfEndpoint
                                        .ForContract(typeof(IUploadService))
                                        .BoundTo(new BasicHttpBinding
                                        {
                                            Security =
                                                {
                                                    Mode = BasicHttpSecurityMode.TransportCredentialOnly,
                                                    Transport = {ClientCredentialType = HttpClientCredentialType.Windows}
                                                }
                                        })))
                );
        }
Exemple #24
0
        static void Main(string[] args)
        {
            Uri[] baseAddresses = new Uri[] {
                new Uri("net.tcp://localhost:8888"),
                new Uri("http://localhost:8889")
            };

            using (ServiceHost host = new ServiceHost(typeof(SecurityService), baseAddresses))
            {
                host.AddServiceEndpoint(typeof(ISecurityService), new NetTcpBinding(), "");

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

                host.Description.Behaviors.Add(serviceBehavior);

                ServiceDebugBehavior debugBehavior = host.Description.Behaviors.Find<ServiceDebugBehavior>();

                if (debugBehavior != null)
                {
                    debugBehavior.IncludeExceptionDetailInFaults = true;
                }
                else
                {
                    debugBehavior = new ServiceDebugBehavior();
                    debugBehavior.IncludeExceptionDetailInFaults = true;

                    host.Description.Behaviors.Add(debugBehavior);
                }

                host.Open();

                Console.WriteLine("Host is running ... Press <Enter> key to stop");
                Console.ReadKey();
            }
        }
      static void Main(string[] args)
      {
        setupLoggers();
        Log cOut = Logger.Instance.getLog(LoggerDefine.OUT_CONSOLE);
        // Create a WSHttpBinding instance
        WSHttpBinding binding = new WSHttpBinding();
        binding.Security.Mode = SecurityMode.None;

        binding.Namespace = "http://abc4trust-uprove/Service1";
        string baseAddress = "http://127.0.0.1:8080/abc4trust-webservice/";

        if (args.Length > 0)
        {
          try
          {
            int port = int.Parse(args[0]);
            cOut.write("Starting UProve WebService on port: " + port);
          }
          catch (Exception ex)
          {
            cOut.write("Exception while parsing port number from args: " + ex.Message);
            DebugUtils.DebugPrint(ex.StackTrace.ToString());
          }

          baseAddress = "http://127.0.0.1:" + args[0] + "/abc4trust-webservice/";
        }
        
        try
        {
          FlatWsdlServiceHost host = new FlatWsdlServiceHost(typeof(Service1));

          // Check to see if the service host already has a ServiceMetadataBehavior
          System.ServiceModel.Description.ServiceMetadataBehavior smb = host.Description.Behaviors.Find<ServiceMetadataBehavior>();
          System.ServiceModel.Description.ServiceDebugBehavior sdb = host.Description.Behaviors.Find<ServiceDebugBehavior>();

          // If not, add one
          if (smb == null)
          {
            smb = new ServiceMetadataBehavior();
          }

          if (sdb == null)
          {
            sdb = new ServiceDebugBehavior();
          }

          sdb.IncludeExceptionDetailInFaults = true;
          smb.HttpGetEnabled = true;
          smb.HttpGetUrl = new Uri(baseAddress + "wsdl");

          cOut.write("Fetch WSDL using .NET on Windows at: " + smb.HttpGetUrl.ToString());

          host.Description.Behaviors.Add(smb);

          // add time profile logger if needed.
          if (ParseConfigManager.SetupTimeProfiles())
          {
            WcfProfileLogger pExt = new WcfProfileLogger();
            host.Description.Behaviors.Add(pExt);
          }
          // Add a service endpoint using the created binding
          ServiceEndpoint endp = host.AddServiceEndpoint(typeof(IService1), binding, baseAddress);
          endp.Behaviors.Add(new FlatWsdl());

          host.Open();
          cOut.write("UProve WebService listening on {0} . . .", baseAddress);
          cOut.write("Press Enter to exit");
          Console.ReadLine();
          host.Close();

        }
        catch (Exception ex)
        {
          cOut.write("Exception while running UProve WebService: " + ex.Message);
          DebugUtils.DebugPrint(ex.StackTrace.ToString());
        }
      }
Exemple #26
0
 /// <summary>
 /// 处理当前主机节点,将当前节点做为服务HOST启动
 /// </summary>
 /// <param name="node">当前主机节点</param>
 private void ProcessNode(NetNode node)
 {
     if (node.Info != null && !string.IsNullOrEmpty(node.Info.Url))
     {
         ServiceHost host = new ServiceHost(typeof(SyncService));
         //if (host.State == CommunicationState.Created)
         //{
         //    _logger.Info(string.Format("主机节点{0}已启动", node.Info.Url));
         //    return;
         //}
         NetTcpBinding binding = new NetTcpBinding("SyncBinding");
         host.AddServiceEndpoint(typeof(ISyncService), binding, node.Info.Url);
         ContractDescription cd = host.Description.Endpoints[0].Contract;
         OperationDescription myOperationDescription = cd.Operations.Find("Excute");
         DataContractSerializerOperationBehavior serializerBehavior = myOperationDescription.Behaviors.Find<DataContractSerializerOperationBehavior>();
         if (serializerBehavior == null)
         {
             serializerBehavior = new DataContractSerializerOperationBehavior(myOperationDescription);
             myOperationDescription.Behaviors.Add(serializerBehavior);
         }
         serializerBehavior.MaxItemsInObjectGraph = 1000000000;
         ServiceDebugBehavior behavior = host.Description.Behaviors.Find<ServiceDebugBehavior>();
         if (behavior == null)
         {
             behavior = new ServiceDebugBehavior();
             host.Description.Behaviors.Add(behavior);
         }
         behavior.IncludeExceptionDetailInFaults = true;
         host.Opened += (obj, e) => { _logger.Info(string.Format("主机节点{0}已启动", node.Info.Url)); };
         host.Open();
     }
     else
     {
         _logger.Error("没有找到可用于启动的主机节点");
     }
 }
Exemple #27
0
        public static Uri RegisterService(Type contract)
        {
            // See if contractType is decorated with the RemoteServiceClassAttribute
            var attr = contract.GetCustomAttributes(typeof(RemoteServiceClassAttribute), false);

            if (attr == null || attr.Length != 1)
            {
                // TODO
                throw new InvalidOperationException("Contracts must be decorated with the RemoteServiceClassAttribute for automatic service registration.");
            }

            var serviceType = ((RemoteServiceClassAttribute)attr[0]).Type.AssemblyQualifiedName;

            // Attempt to load type
            var service = Type.GetType(serviceType);

            if (!service.IsSubclassOf(typeof(RemoteServiceBase)))
            {
                // TODO
                throw new InvalidOperationException("Service class must derive from Jhu.Graywulf.RemoteService.RemoteServiceBase");
            }

            if (service == null || contract == null)
            {
                throw new Exception("Type not found.");    // TODO
            }

            // Everything is OK, initialize service

            lock (syncRoot)
            {
                var host = new ServiceHost(
                    service,
                    RemoteServiceHelper.CreateEndpointUri(RemoteServiceHelper.GetFullyQualifiedDnsName(), ""));

                // Turn on detailed debug info
                var sdb = host.Description.Behaviors.Find<ServiceDebugBehavior>();
                if (sdb == null)
                {
                    sdb = new ServiceDebugBehavior();
                    host.Description.Behaviors.Add(sdb);
                }
                sdb.IncludeExceptionDetailInFaults = true;

                // Turn on impersonation
                /*
                var sab = host.Description.Behaviors.Find<ServiceAuthorizationBehavior>();
                if (sab == null)
                {
                    sab = new ServiceAuthorizationBehavior();
                    host.Description.Behaviors.Add(sab);
                }
                sab.ImpersonateCallerForAllOperations = true;
                */

                // Unthrottle service to increase throughput
                // Service is behind a firewall, no DOS attacks will happen
                // TODO: copy these settings to the control endpoint
                var tb = host.Description.Behaviors.Find<ServiceThrottlingBehavior>();
                if (tb == null)
                {
                    tb = new ServiceThrottlingBehavior();
                    host.Description.Behaviors.Add(tb);
                }
                tb.MaxConcurrentCalls = 1024;
                tb.MaxConcurrentInstances = Int32.MaxValue;
                tb.MaxConcurrentSessions = 1024;

                var endpoint = host.AddServiceEndpoint(
                    contract,
                    RemoteServiceHelper.CreateNetTcpBinding(),
                    RemoteServiceHelper.CreateEndpointUri(RemoteServiceHelper.GetFullyQualifiedDnsName(), service.FullName));

                host.Open();

                registeredServiceHosts.Add(contract.FullName, host);
                registeredEndpoints.Add(contract.FullName, endpoint);

                return endpoint.Address.Uri;
            }
        }
Exemple #28
0
        static void Main(string[] args)
        {
            setupLoggers();
            Log cOut = Logger.Instance.getLog(LoggerDefine.OUT_CONSOLE);
            // Create a WSHttpBinding instance
            WSHttpBinding binding = new WSHttpBinding();

            binding.Security.Mode = SecurityMode.None;

            binding.Namespace = "http://abc4trust-uprove/Service1";
            string baseAddress = "http://127.0.0.1:8080/abc4trust-webservice/";

            if (args.Length > 0)
            {
                try
                {
                    int port = int.Parse(args[0]);
                    cOut.write("Starting UProve WebService on port: " + port);
                }
                catch (Exception ex)
                {
                    cOut.write("Exception while parsing port number from args: " + ex.Message);
                    DebugUtils.DebugPrint(ex.StackTrace.ToString());
                }

                baseAddress = "http://127.0.0.1:" + args[0] + "/abc4trust-webservice/";
            }

            try
            {
                FlatWsdlServiceHost host = new FlatWsdlServiceHost(typeof(Service1));

                // Check to see if the service host already has a ServiceMetadataBehavior
                System.ServiceModel.Description.ServiceMetadataBehavior smb = host.Description.Behaviors.Find <ServiceMetadataBehavior>();
                System.ServiceModel.Description.ServiceDebugBehavior    sdb = host.Description.Behaviors.Find <ServiceDebugBehavior>();

                // If not, add one
                if (smb == null)
                {
                    smb = new ServiceMetadataBehavior();
                }

                if (sdb == null)
                {
                    sdb = new ServiceDebugBehavior();
                }

                sdb.IncludeExceptionDetailInFaults = true;
                smb.HttpGetEnabled = true;
                smb.HttpGetUrl     = new Uri(baseAddress + "wsdl");

                cOut.write("Fetch WSDL using .NET on Windows at: " + smb.HttpGetUrl.ToString());

                host.Description.Behaviors.Add(smb);

                // add time profile logger if needed.
                if (ParseConfigManager.SetupTimeProfiles())
                {
                    WcfProfileLogger pExt = new WcfProfileLogger();
                    host.Description.Behaviors.Add(pExt);
                }
                // Add a service endpoint using the created binding
                ServiceEndpoint endp = host.AddServiceEndpoint(typeof(IService1), binding, baseAddress);
                endp.Behaviors.Add(new FlatWsdl());

                host.Open();
                cOut.write("UProve WebService listening on {0} . . .", baseAddress);
                cOut.write("Press Enter to exit");
                Console.ReadLine();
                host.Close();
            }
            catch (Exception ex)
            {
                cOut.write("Exception while running UProve WebService: " + ex.Message);
                DebugUtils.DebugPrint(ex.StackTrace.ToString());
            }
        }
        public void ApplyDispatchBehavior(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
        {
            if (serviceDescription == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("serviceDescription");
            }

            if (serviceHostBase == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("serviceHostBase");
            }

            if (serviceDescription.Endpoints == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("serviceDescription", SR2.GetString(SR2.NoEndpoints));
            }

            PersistenceProviderBehavior providerBehavior = null;

            if (serviceDescription.Behaviors != null)
            {
                providerBehavior = serviceDescription.Behaviors.Find <PersistenceProviderBehavior>();
            }

            if (providerBehavior == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                          new InvalidOperationException(
                              SR2.GetString(
                                  SR2.NonNullPersistenceProviderRequired,
                                  typeof(PersistenceProvider).Name,
                                  typeof(DurableServiceAttribute).Name)));
            }

            if (providerBehavior.PersistenceProviderFactory == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                          new InvalidOperationException(
                              SR2.GetString(
                                  SR2.NonNullPersistenceProviderRequired,
                                  typeof(PersistenceProvider).Name,
                                  typeof(DurableServiceAttribute).Name)));
            }

            providerBehavior.PersistenceProviderFactory.Open();
            serviceHostBase.Closed += new EventHandler(
                delegate(object sender, EventArgs args)
            {
                Fx.Assert(sender is ServiceHostBase, "The sender should be serviceHostBase.");
                // We have no way of knowing whether the service host closed or aborted
                // so we err on the side of abort for right now.
                providerBehavior.PersistenceProviderFactory.Abort();
            }
                );

            DurableInstanceContextProvider instanceContextProvider = new ServiceDurableInstanceContextProvider(
                serviceHostBase,
                false,
                serviceDescription.ServiceType,
                providerBehavior.PersistenceProviderFactory,
                this.saveStateInOperationTransaction,
                this.unknownExceptionAction,
                new DurableRuntimeValidator(this.saveStateInOperationTransaction, this.unknownExceptionAction),
                providerBehavior.PersistenceOperationTimeout);

            DurableInstanceContextProvider singleCallInstanceContextProvider = null;

            IInstanceProvider instanceProvider = new DurableInstanceProvider(instanceContextProvider);

            bool includeExceptionDetails = false;

            if (serviceDescription.Behaviors != null)
            {
                ServiceBehaviorAttribute serviceBehavior = serviceDescription.Behaviors.Find <ServiceBehaviorAttribute>();

                if (serviceBehavior != null)
                {
                    includeExceptionDetails |= serviceBehavior.IncludeExceptionDetailInFaults;
                }

                ServiceDebugBehavior serviceDebugBehavior = serviceDescription.Behaviors.Find <ServiceDebugBehavior>();

                if (serviceDebugBehavior != null)
                {
                    includeExceptionDetails |= serviceDebugBehavior.IncludeExceptionDetailInFaults;
                }
            }

            IErrorHandler errorHandler = new ServiceErrorHandler(includeExceptionDetails);

            foreach (ChannelDispatcherBase channelDispatcherBase in serviceHostBase.ChannelDispatchers)
            {
                ChannelDispatcher channelDispatcher = channelDispatcherBase as ChannelDispatcher;

                if (channelDispatcher != null && channelDispatcher.HasApplicationEndpoints())
                {
                    if (this.unknownExceptionAction == UnknownExceptionAction.AbortInstance)
                    {
                        channelDispatcher.ErrorHandlers.Add(errorHandler);
                    }

                    foreach (EndpointDispatcher endpointDispatcher in channelDispatcher.Endpoints)
                    {
                        if (endpointDispatcher.IsSystemEndpoint)
                        {
                            continue;
                        }
                        ServiceEndpoint serviceEndPoint = serviceDescription.Endpoints.Find(new XmlQualifiedName(endpointDispatcher.ContractName, endpointDispatcher.ContractNamespace));

                        if (serviceEndPoint != null)
                        {
                            if (serviceEndPoint.Contract.SessionMode != SessionMode.NotAllowed)
                            {
                                endpointDispatcher.DispatchRuntime.InstanceContextProvider = instanceContextProvider;
                            }
                            else
                            {
                                if (singleCallInstanceContextProvider == null)
                                {
                                    singleCallInstanceContextProvider = new ServiceDurableInstanceContextProvider(
                                        serviceHostBase,
                                        true,
                                        serviceDescription.ServiceType,
                                        providerBehavior.PersistenceProviderFactory,
                                        this.saveStateInOperationTransaction,
                                        this.unknownExceptionAction,
                                        new DurableRuntimeValidator(this.saveStateInOperationTransaction, this.unknownExceptionAction),
                                        providerBehavior.PersistenceOperationTimeout);
                                }
                                endpointDispatcher.DispatchRuntime.InstanceContextProvider = singleCallInstanceContextProvider;
                            }
                            endpointDispatcher.DispatchRuntime.MessageInspectors.Add(new DurableMessageDispatchInspector(serviceEndPoint.Contract.SessionMode));
                            endpointDispatcher.DispatchRuntime.InstanceProvider = instanceProvider;
                            WorkflowServiceBehavior.SetContractFilterToIncludeAllOperations(endpointDispatcher, serviceEndPoint.Contract);
                        }
                    }
                }
            }

            foreach (ServiceEndpoint endpoint in serviceDescription.Endpoints)
            {
                if (!endpoint.InternalIsSystemEndpoint(serviceDescription))
                {
                    foreach (OperationDescription opDescription in endpoint.Contract.Operations)
                    {
                        if (!opDescription.Behaviors.Contains(typeof(DurableOperationAttribute)))
                        {
                            opDescription.Behaviors.Add(DurableOperationAttribute.DefaultInstance);
                        }
                    }
                }
            }
        }
		public void Defaults () {
			ServiceDebugBehavior behavior = new ServiceDebugBehavior ();
			Assert.AreEqual (true, behavior.HttpHelpPageEnabled, "HttpHelpPageEnabled");
			Assert.IsNull (behavior.HttpHelpPageUrl, "HttpHelpPageUrl");
			Assert.AreEqual (true, behavior.HttpsHelpPageEnabled, "HttpsHelpPageEnabled");
			Assert.IsNull (behavior.HttpsHelpPageUrl, "HttpsHelpPageUrl");
			Assert.AreEqual (false, behavior.IncludeExceptionDetailInFaults, "IncludeExceptionDetailInFaults");
		}
        /// <summary>
        /// Applies the service host settings.
        /// </summary>
        /// <param name="host">Host.</param>
        /// <param name="useCustomBehaviours">If set to <c>true</c> use custom behaviours.</param>
        private static void ApplyServiceHostSettings(ServiceHost host, bool useCustomBehaviours = false)
        {
            host.OpenTimeout = host.CloseTimeout = _timeout;

            ServiceDebugBehavior sdb = host.Description.Behaviors.Find<ServiceDebugBehavior>();
            if (sdb == null)
                host.Description.Behaviors.Add(sdb = new ServiceDebugBehavior());
            sdb.IncludeExceptionDetailInFaults = true;

            host.AddServiceEndpoint(typeof(IRepository),
                new NetTcpBinding(SecurityMode.None)
                {
                    MaxBufferSize = 4096,
                    ReaderQuotas = new System.Xml.XmlDictionaryReaderQuotas()
                    {
                        MaxStringContentLength = 32768
                    }
                },
                new Uri("net.tcp://localhost:3334/ArtefactRepository"));

            if (useCustomBehaviours)
                ApplyServiceHostBehaviours(host);

            host.Opened += (sender, e) => _output.WriteLine("{0}: Opened", host.GetType().Name);
            host.Opening += (sender, e) => _output.WriteLine("{0}: Opening", host.GetType().Name);
            host.Closed += (sender, e) => _output.WriteLine("{0}: Closed", host.GetType().Name);
            host.Closing += (sender, e) => _output.WriteLine("{0}: Closing", host.GetType().Name);
            host.Faulted += (sender, e) => _error.WriteLine("{0}: Faulted", host.GetType().Name);
            host.UnknownMessageReceived += (sender, e) => _error.WriteLine("{0}: UnknownMessageReceived", host.GetType().Name);
        }
Exemple #32
0
        /// <summary>
        /// host
        /// </summary>
        /// <param name="point"></param>
        /// <param name="debugbehavior"></param>
        /// <param name="throtbehavior"></param>
        /// <param name="bing"></param>
        private void OpenHost(ServicePoint point, ServiceDebugBehavior debugbehavior, ServiceThrottlingBehavior throtbehavior, NetTcpBinding bing, bool EnableBinaryFormatterBehavior,Uri baseAddress)
        {
            ServiceHost host = new ServiceHost(point.Name, new Uri("net.tcp://" + baseAddress));
            #region behavior
            if (host.Description.Behaviors.Find<ServiceDebugBehavior>() != null)
                host.Description.Behaviors.Remove<ServiceDebugBehavior>();
            if (host.Description.Behaviors.Find<ServiceThrottlingBehavior>() != null)
                host.Description.Behaviors.Remove<ServiceThrottlingBehavior>();

            host.Description.Behaviors.Add(debugbehavior);
            host.Description.Behaviors.Add(throtbehavior);

            //大数据量传输时必须设定此参数
            if (point.MaxItemsInObjectGraph != null)
            {
                if (host.Description.Behaviors.Find<DataContractSerializerOperationBehavior>() != null)
                    host.Description.Behaviors.Remove<DataContractSerializerOperationBehavior>();
                //通过反射指定MaxItemsInObjectGraph属性(传输大数据时使用)
                object obj = typeof(ServiceHost).Assembly.CreateInstance(
                        "System.ServiceModel.Dispatcher.DataContractSerializerServiceBehavior"
                        , true, BindingFlags.CreateInstance | BindingFlags.Instance | BindingFlags.NonPublic
                        , null, new object[] { false, (int)point.MaxItemsInObjectGraph }, null, null);
                IServiceBehavior datacontractbehavior = obj as IServiceBehavior;
                host.Description.Behaviors.Add(datacontractbehavior);
            }
            #endregion

            host.AddServiceEndpoint(point.Contract, bing, (point.Address.StartsWith("/") ? point.Address.TrimStart('/') : point.Address));

            //自定义二进制序列化器
            if (EnableBinaryFormatterBehavior)
            {
                System.ServiceModel.Description.ServiceEndpoint spoint = host.Description.Endpoints.Count == 1 ? host.Description.Endpoints[0] : null;
                if (spoint != null && spoint.Behaviors.Find<BinaryFormatterBehavior>() == null)
                {
                    BinaryFormatterBehavior serializeBehavior = new BinaryFormatterBehavior();
                    spoint.Behaviors.Add(serializeBehavior);
                }
            }

            #region 增加拦截器处理
            if (point.Address != "Com/FrameWork/Helper/Wcf/LoadBalance/IHeatBeat" && point.Address != "Com/FrameWork/Helper/Wcf/Monitor/IMonitorControl")
            {
                int endpointscount = host.Description.Endpoints.Count;
                WcfParameterInspector wcfpi = new WcfParameterInspector();
                wcfpi.WcfAfterCallEvent += new Wcf.WcfAfterCall((operationName, outputs, returnValue, correlationState, AbsolutePath) =>
                {
                    if (WcfAfterCallEvent != null)
                    {
                        WcfAfterCallEvent(operationName, outputs, returnValue, correlationState, AbsolutePath);
                    }
                });
                wcfpi.WcfBeforeCallEvent += new Wcf.WcfBeforeCall((operationName, inputs, AbsolutePath, correlationState) =>
                {
                    if (WcfBeforeCallEvent != null)
                    {
                        WcfBeforeCallEvent(operationName, inputs, AbsolutePath, correlationState);
                    }
                });
                for (int i = 0; i < endpointscount; i++)
                {
                    if (host.Description.Endpoints[i].Contract.Name != "IMetadataExchange")
                    {
                        int Operationscount = host.Description.Endpoints[i].Contract.Operations.Count;
                        for (int j = 0; j < Operationscount; j++)
                        {
                            host.Description.Endpoints[i].Contract.Operations[j].Behaviors.Add(wcfpi);
                        }
                    }
                }
            }
            #endregion

            #region 注册事件
            //错误状态处理
            host.Faulted += new EventHandler((sender, e) =>
            {
                if (WcfFaultedEvent != null)
                {
                    WcfFaultedEvent(sender, e);
                }
            });
            //关闭状态处理
            host.Closed += new EventHandler((sender, e) =>
            {
                if (WcfClosedEvent != null)
                {
                    WcfClosedEvent(sender, e);
                }

                //如果意外关闭,再次打开监听
                if (isStop)
                    return;

                services.Remove(host);
                OpenHost(point, debugbehavior, throtbehavior, bing, EnableBinaryFormatterBehavior,baseAddress);
            });
            #endregion

            host.Open();
            services.Add(host);
        }
Exemple #33
0
        // Start WCF Service to manage VM
        private IVMManager StartVMManagerService()
        {
            try
            {
                // If available, get SSL certificate from service configuration
                string sslCertificateSHA1Thumbprint = null;
                try
                {
                    sslCertificateSHA1Thumbprint = RoleEnvironment.GetConfigurationSettingValue("SSLCertificateSHA1Thumbprint");
                }
                catch (Exception)
                {
                    // Ignore, it means SSLCertificateSHA1Thumbprint is not defined
                }

                // Get VMManager WCF service binding
                BasicHttpBinding binding = WindowsAzureVMManager.GetVMManagerServiceBinding(sslCertificateSHA1Thumbprint);                
                wcfVMManagerServiceHost = new ServiceHost(typeof(WindowsAzureVMManager));
                wcfVMManagerServiceHost.Credentials.UserNameAuthentication.UserNamePasswordValidationMode = UserNamePasswordValidationMode.Custom;
                wcfVMManagerServiceHost.Credentials.UserNameAuthentication.CustomUserNamePasswordValidator = new WindowsAzureVMManagerUsernamePasswordValidator();

                UseRequestHeadersForMetadataAddressBehavior requestHeaderBehavior = new UseRequestHeadersForMetadataAddressBehavior();
                IPEndPoint ep = WindowsAzureVMManager.GetVMManagerServiceEndpoint(sslCertificateSHA1Thumbprint);  
                if (string.IsNullOrEmpty(sslCertificateSHA1Thumbprint))
                {
                    requestHeaderBehavior.DefaultPortsByScheme.Add("http", int.Parse(ep.Port.ToString()));
                }
                else
                {
                    requestHeaderBehavior.DefaultPortsByScheme.Add("https", int.Parse(ep.Port.ToString()));
                    wcfVMManagerServiceHost.Credentials.ServiceCertificate.SetCertificate(
                        StoreLocation.LocalMachine,
                        StoreName.My,
                        X509FindType.FindByThumbprint,
                        RoleEnvironment.GetConfigurationSettingValue("SSLCertificateSHA1Thumbprint")
                    );
                }
                wcfVMManagerServiceHost.Description.Behaviors.Add(requestHeaderBehavior);                

                // Enable WCF service debugging
                ServiceDebugBehavior sdb = wcfVMManagerServiceHost.Description.Behaviors.Find<ServiceDebugBehavior>();
                if (sdb == null)
                {
                    sdb = new ServiceDebugBehavior();
                    wcfVMManagerServiceHost.Description.Behaviors.Add(sdb);
                }
                sdb.IncludeExceptionDetailInFaults = true;

                string endpoint = WindowsAzureVMManager.GetVMManagerServiceEndpointAddress(sslCertificateSHA1Thumbprint);
                wcfVMManagerServiceHost.AddServiceEndpoint(typeof(IVMManager), binding, endpoint);
                
                ServiceMetadataBehavior metadataBehavior = new ServiceMetadataBehavior();                
                if (string.IsNullOrEmpty(sslCertificateSHA1Thumbprint))
                {
                    metadataBehavior.HttpGetEnabled = true;
                    metadataBehavior.HttpGetUrl = new Uri(endpoint);
                }
                else
                {
                    metadataBehavior.HttpsGetEnabled = true;
                    metadataBehavior.HttpsGetUrl = new Uri(endpoint);
                }                   
                                
                wcfVMManagerServiceHost.Description.Behaviors.Add(metadataBehavior);

                wcfVMManagerServiceHost.Open();
                Trace.TraceInformation("External WCF Service started on endpoint: {0}", endpoint);                
            }
            catch (Exception ex)
            {
                Trace.TraceError(ex.Message);
                Trace.TraceError(ex.StackTrace);
            }

            // Return service instance
            return WindowsAzureVMManager.GetVMManager();
        }
        public void ApplyDispatchBehavior(ServiceDescription description, ServiceHostBase serviceHostBase)
        {
            if (description == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("description");
            }

            if (serviceHostBase == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("serviceHostBase");
            }
            if (description.Behaviors == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("description", SR2.GetString(SR2.NoBehaviors));
            }
            if (description.Endpoints == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("description", SR2.GetString(SR2.NoEndpoints));
            }

            bool syncContextRegistered = false;
            WorkflowRuntimeBehavior workflowRuntimeBehavior = description.Behaviors.Find <WorkflowRuntimeBehavior>();

            if (workflowRuntimeBehavior == null)
            {
                workflowRuntimeBehavior = new WorkflowRuntimeBehavior();
                description.Behaviors.Add(workflowRuntimeBehavior);
            }

            WorkflowPersistenceService persistenceService = workflowRuntimeBehavior.WorkflowRuntime.GetService <WorkflowPersistenceService>();

            if (persistenceService != null)
            {
                bool wasRuntimeStarted = workflowRuntimeBehavior.WorkflowRuntime.IsStarted;
                if (wasRuntimeStarted)
                {
                    workflowRuntimeBehavior.WorkflowRuntime.StopRuntime();
                }
                workflowRuntimeBehavior.WorkflowRuntime.RemoveService(persistenceService);
                workflowRuntimeBehavior.WorkflowRuntime.AddService(new SkipUnloadOnFirstIdleWorkflowPersistenceService(persistenceService));
                if (wasRuntimeStarted)
                {
                    workflowRuntimeBehavior.WorkflowRuntime.StartRuntime();
                }
            }

            this.workflowDefinitionContext.Register(workflowRuntimeBehavior.WorkflowRuntime, workflowRuntimeBehavior.ValidateOnCreate);

            WorkflowInstanceContextProvider instanceContextProvider = new WorkflowInstanceContextProvider(
                serviceHostBase,
                false,
                this.workflowDefinitionContext
                );

            WorkflowInstanceContextProvider singleCallInstanceContextProvider = null;

            IInstanceProvider    instanceProvider     = new WorkflowInstanceProvider(instanceContextProvider);
            ServiceDebugBehavior serviceDebugBehavior = description.Behaviors.Find <ServiceDebugBehavior>();

            bool includeExceptionDetailsInFaults = this.IncludeExceptionDetailInFaults;

            if (serviceDebugBehavior != null)
            {
                includeExceptionDetailsInFaults |= serviceDebugBehavior.IncludeExceptionDetailInFaults;
            }

            IErrorHandler workflowOperationErrorHandler = new WorkflowOperationErrorHandler(includeExceptionDetailsInFaults);

            foreach (ChannelDispatcherBase channelDispatcherBase in serviceHostBase.ChannelDispatchers)
            {
                ChannelDispatcher channelDispatcher = channelDispatcherBase as ChannelDispatcher;

                if (channelDispatcher != null && channelDispatcher.HasApplicationEndpoints())
                {
                    channelDispatcher.IncludeExceptionDetailInFaults = includeExceptionDetailsInFaults;
                    channelDispatcher.ErrorHandlers.Add(workflowOperationErrorHandler);
                    foreach (EndpointDispatcher endPointDispatcher in channelDispatcher.Endpoints)
                    {
                        if (endPointDispatcher.IsSystemEndpoint)
                        {
                            continue;
                        }

                        ServiceEndpoint serviceEndPoint = description.Endpoints.Find(new XmlQualifiedName(endPointDispatcher.ContractName, endPointDispatcher.ContractNamespace));

                        if (serviceEndPoint != null)
                        {
                            DispatchRuntime dispatchRuntime = endPointDispatcher.DispatchRuntime;

                            dispatchRuntime.AutomaticInputSessionShutdown = true;
                            dispatchRuntime.ConcurrencyMode        = ConcurrencyMode.Single;
                            dispatchRuntime.ValidateMustUnderstand = this.ValidateMustUnderstand;

                            if (!this.UseSynchronizationContext)
                            {
                                dispatchRuntime.SynchronizationContext = null;
                            }
                            else if (!syncContextRegistered)
                            {
                                SynchronizationContextWorkflowSchedulerService syncSchedulerService = workflowRuntimeBehavior.WorkflowRuntime.GetService <SynchronizationContextWorkflowSchedulerService>();
                                Fx.Assert(syncSchedulerService != null, "Wrong Synchronization Context Set");
                                syncSchedulerService.SetSynchronizationContext(dispatchRuntime.SynchronizationContext);
                                syncContextRegistered = true;
                            }

                            if (!endPointDispatcher.AddressFilterSetExplicit)
                            {
                                EndpointAddress endPointAddress = endPointDispatcher.OriginalAddress;
                                if ((endPointAddress == null) || (this.AddressFilterMode == AddressFilterMode.Any))
                                {
                                    endPointDispatcher.AddressFilter = new MatchAllMessageFilter();
                                }
                                else if (this.AddressFilterMode == AddressFilterMode.Prefix)
                                {
                                    endPointDispatcher.AddressFilter = new PrefixEndpointAddressMessageFilter(endPointAddress);
                                }
                                else if (this.AddressFilterMode == AddressFilterMode.Exact)
                                {
                                    endPointDispatcher.AddressFilter = new EndpointAddressMessageFilter(endPointAddress);
                                }
                            }

                            if (serviceEndPoint.Contract.SessionMode != SessionMode.NotAllowed)
                            {
                                endPointDispatcher.DispatchRuntime.InstanceContextProvider = instanceContextProvider;
                            }
                            else
                            {
                                if (singleCallInstanceContextProvider == null)
                                {
                                    singleCallInstanceContextProvider = new WorkflowInstanceContextProvider(
                                        serviceHostBase,
                                        true,
                                        this.workflowDefinitionContext);
                                }
                                endPointDispatcher.DispatchRuntime.InstanceContextProvider = singleCallInstanceContextProvider;
                            }
                            endPointDispatcher.DispatchRuntime.MessageInspectors.Add(new DurableMessageDispatchInspector(serviceEndPoint.Contract.SessionMode));
                            endPointDispatcher.DispatchRuntime.InstanceProvider = instanceProvider;
                            SetContractFilterToIncludeAllOperations(endPointDispatcher, serviceEndPoint.Contract);
                        }
                    }
                }
            }
            DataContractSerializerServiceBehavior.ApplySerializationSettings(description, this.ignoreExtensionDataObject, this.maxItemsInObjectGraph);
        }