Ejemplo n.º 1
0
        protected internal void DeployAppConfig()
        {
            IOUtil.FindAndWriteResourceToFile(this.GetType().Assembly, "app.config", ExecutablePath + ".config");

            Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ExecutablePath);
#if !ClientSKUFramework
            if (AstoriaTestProperties.Host == Host.WebServiceHost)
            {
                BindingsSection bindingsSection = config.GetSection("system.serviceModel/bindings") as BindingsSection;
                WebHttpBindingCollectionElement webHttpBindingCollectionElement;
                WebHttpBindingElement           webHttpBindingElement;
                foreach (BindingCollectionElement bindingCollectionElement in bindingsSection.BindingCollections)
                {
                    // find WebHttpBinding element "higherMessageSize" and modify its settings
                    if (bindingCollectionElement.BindingType.ToString().Equals("System.ServiceModel.WebHttpBinding"))
                    {
                        webHttpBindingCollectionElement = bindingCollectionElement as WebHttpBindingCollectionElement;
                        webHttpBindingElement           = webHttpBindingCollectionElement.Bindings["higherMessageSize"];

                        if (webHttpBindingElement != null)
                        {
                            // webHttpBinding -> binding -> security ->transport
                            WebHttpSecurityElement webHttpSecurityElement = webHttpBindingElement.Security;
                            switch (AstoriaTestProperties.HostAuthenicationMethod.ToLower())
                            {
                            case "windows":
                                webHttpSecurityElement.Transport.ClientCredentialType = System.ServiceModel.HttpClientCredentialType.Windows;
                                webHttpSecurityElement.Transport.ProxyCredentialType  = System.ServiceModel.HttpProxyCredentialType.Windows;
                                break;

                            default:
                                webHttpSecurityElement.Transport.ClientCredentialType = System.ServiceModel.HttpClientCredentialType.None;
                                webHttpSecurityElement.Transport.ProxyCredentialType  = System.ServiceModel.HttpProxyCredentialType.None;
                                break;
                            }
                        }
                    }
                }
            }
#endif

            if (Database != null)
            {
                // fixup config files
                config.ConnectionStrings.ConnectionStrings.Clear();
                config.ConnectionStrings.ConnectionStrings.Add(this.Workspace.GetConnectionStringSettingsForProvider(this, this.Database.DatabaseConnectionString));
            }

            config.Save();

            if (AstoriaTestProperties.WebServiceHostTargetFramework != null)
            {
                //Would rather do this through the API but unsure how
                string contents         = File.ReadAllText(ExecutablePath + ".config");
                int    configurationPos = contents.IndexOf("<configuration>");
                string startupStr       = string.Format("<startup><supportedRuntime version=\"{0}\"/></startup>", AstoriaTestProperties.WebServiceHostTargetFramework);
                contents = contents.Insert(configurationPos + 16, startupStr);
                File.WriteAllText(ExecutablePath + ".config", contents);
            }
        }
Ejemplo n.º 2
0
        public BasicHttpBinding(string configurationName) : this()
        {
            BindingsSection         bindingsSection = Configuration.ConfigUtil.BindingsSection;
            BasicHttpBindingElement el = bindingsSection.BasicHttpBinding.Bindings[configurationName];

            el.ApplyConfiguration(this);
        }
Ejemplo n.º 3
0
        internal static BindingCollectionElement UnsafeGetAssociatedBindingCollectionElement(ContextInformation evaluationContext, string bindingCollectionName)
        {
            BindingCollectionElement item            = null;
            BindingsSection          bindingsSection = (BindingsSection)Microsoft.ServiceBus.Configuration.ConfigurationHelpers.UnsafeGetAssociatedSection(evaluationContext, Microsoft.ServiceBus.Configuration.ConfigurationStrings.BindingsSectionGroupPath);

            if (bindingsSection != null)
            {
                try
                {
                    item = bindingsSection[bindingCollectionName];
                }
                catch (KeyNotFoundException keyNotFoundException)
                {
                    ExceptionUtility exceptionUtility = Microsoft.ServiceBus.Diagnostics.DiagnosticUtility.ExceptionUtility;
                    string           configBindingExtensionNotFound = Resources.ConfigBindingExtensionNotFound;
                    object[]         bindingsSectionPath            = new object[] { Microsoft.ServiceBus.Configuration.ConfigurationHelpers.GetBindingsSectionPath(bindingCollectionName) };
                    throw exceptionUtility.ThrowHelperError(new ConfigurationErrorsException(Microsoft.ServiceBus.SR.GetString(configBindingExtensionNotFound, bindingsSectionPath)));
                }
                catch (NullReferenceException nullReferenceException)
                {
                    ExceptionUtility exceptionUtility1 = Microsoft.ServiceBus.Diagnostics.DiagnosticUtility.ExceptionUtility;
                    string           str      = Resources.ConfigBindingExtensionNotFound;
                    object[]         objArray = new object[] { Microsoft.ServiceBus.Configuration.ConfigurationHelpers.GetBindingsSectionPath(bindingCollectionName) };
                    throw exceptionUtility1.ThrowHelperError(new ConfigurationErrorsException(Microsoft.ServiceBus.SR.GetString(str, objArray)));
                }
            }
            return(item);
        }
        internal ConfigWriter(System.Configuration.Configuration configuration)
        {
            this.bindingsSection = BindingsSection.GetSection(configuration);
            ServiceModelSectionGroup sectionGroup = ServiceModelSectionGroup.GetSectionGroup(configuration);

            this.channels = sectionGroup.Client.Endpoints;
            this.config   = configuration;
        }
Ejemplo n.º 5
0
            public static Binding GetFromConfig(string configurationName)
            {
                var bingingsSection = BindingsSection.GetSection(ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None));
                var bindingType     = (from b in bingingsSection.BindingCollections
                                       where b.ConfiguredBindings.Count > 0 && b.ContainsKey(configurationName)
                                       select b.BindingType).FirstOrDefault();
                var binding = bindingType != null?Activator.CreateInstance(bindingType, configurationName) : null;

                return((Binding)binding);
            }
Ejemplo n.º 6
0
        internal ConfigWriter(Configuration configuration)
        {
            this.bindingTable = new Dictionary <Binding, BindingDictionaryValue>();

            this.bindingsSection = BindingsSection.GetSection(configuration);

            ServiceModelSectionGroup serviceModelSectionGroup = ServiceModelSectionGroup.GetSectionGroup(configuration);

            this.channels = serviceModelSectionGroup.Client.Endpoints;
            this.config   = configuration;
        }
Ejemplo n.º 7
0
        /// <summary>
        /// 获取绑定信息节点
        /// </summary>
        /// <param name="configName">配置名</param>
        /// <returns></returns>
        private static BindingsSection GetBindingsSection(string configName)
        {
            BindingsSection bindingsSection = null;

            SetConfigFile(configName);
            if (config != null)
            {
                bindingsSection = config.GetSection("system.serviceModel/bindings") as BindingsSection;
            }
            return(bindingsSection);
        }
Ejemplo n.º 8
0
        static void Main(string[] args)
        {
            var config          = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            var bingingsSection = BindingsSection.GetSection(config);

            string netTcpSource    = bingingsSection.NetTcpBinding.ElementInformation.Source;
            string basicHttpSource = bingingsSection.BasicHttpBinding.ElementInformation.Source;

            Console.WriteLine("Net TCP Binding came from \"{0}\"", netTcpSource);
            Console.WriteLine("Basic HTTP Binding came from \"{0}\"", basicHttpSource);
        }
Ejemplo n.º 9
0
        private BasicHttpBinding CreateBindingFromConfig()
        {
            ServiceModelSectionGroup config  = (ServiceModelSectionGroup)ConfigurationManager.OpenExeConfiguration("Test/config/basicHttpBinding").GetSectionGroup("system.serviceModel");
            BindingsSection          section = (BindingsSection)config.Bindings;
            BasicHttpBindingElement  el      = section.BasicHttpBinding.Bindings ["BasicHttpBinding2_Service"];

            BasicHttpBinding b = new BasicHttpBinding();

            el.ApplyConfiguration(b);

            return(b);
        }
        internal static WSStreamedHttpBindingCollectionElement GetCollectionElement()
        {
            WSStreamedHttpBindingCollectionElement retVal = null;
            BindingsSection bindingsSection = (BindingsSection)ConfigurationManager.GetSection("system.serviceModel/bindings");

            if (null != bindingsSection)
            {
                retVal = bindingsSection[WSStreamedHttpBindingConstants.WSStreamedHttpBindingCollectionElementName] as WSStreamedHttpBindingCollectionElement;
            }

            return(retVal);
        }
Ejemplo n.º 11
0
        public static AssertEncryptionHttpBindingCollectionElement GetBindingCollectionElement()
        {
            AssertEncryptionHttpBindingCollectionElement bindingCollectionElement = null;

            BindingsSection bindingsSection = ConfigurationManager.GetSection("system.serviceModel/bindings") as BindingsSection;

            if (bindingsSection != null)
            {
                bindingCollectionElement = bindingsSection[AssertEncryptionHttpBindingCollectionElement.BindingCollectionElementName] as AssertEncryptionHttpBindingCollectionElement;
            }

            return(bindingCollectionElement);
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Get Bindings Section
        /// </summary>
        /// <param name="configName"></param>
        /// <returns></returns>
        private static BindingsSection moGetBindingsSection(string configName)
        {
            BindingsSection loBindingSection = null;

            moSetConfigFile(configName);

            if (moConfig != null)
            {
                loBindingSection = moConfig.GetSection("system.serviceModel/bindings") as BindingsSection;
            }

            return(loBindingSection);
        }
Ejemplo n.º 13
0
        public static RouterBindingCollectionElement GetBindingCollectionElement()
        {
            RouterBindingCollectionElement retval = null;

            BindingsSection bindingsSection = (BindingsSection)ConfigurationManager.GetSection("system.serviceModel/bindings");

            if (null != bindingsSection)
            {
                retval = bindingsSection["routerBinding"] as RouterBindingCollectionElement;
            }

            return(retval);
        }
Ejemplo n.º 14
0
        private void ApplyConfiguration(string configurationName)
        {
            BindingsSection bindings = ((BindingsSection)(ConfigurationManager.GetSection("system.serviceModel/bindings")));
            NetHttpBindingCollectionElement section = (NetHttpBindingCollectionElement)bindings["netHttpBinding"];
            NetHttpBindingElement           element = section.Bindings[configurationName];

            if ((element == null))
            {
                throw new System.Configuration.ConfigurationErrorsException(string.Format(CultureInfo.CurrentCulture, "There is no binding named {0} at {1}.", configurationName, section.BindingName));
            }
            else
            {
                element.ApplyConfiguration(this);
            }
        }
        protected internal static Binding ResolveBinding(BindingsSection section, string bindingName, string name)
        {
            var bindingCollection = section.BindingCollections.FirstOrDefault(x => x.BindingName == bindingName);
            var bindingElement    = bindingCollection?.ConfiguredBindings?.FirstOrDefault(x => x.Name == name);

            if (bindingElement == null)
            {
                return(null);
            }
            var binding = (Binding)Activator.CreateInstance(bindingCollection.BindingType);

            binding.Name = bindingElement.Name;
            bindingElement.ApplyConfiguration(binding);
            return(binding);
        }
Ejemplo n.º 16
0
        private static BindingCollectionElement GetBindingCollectionElement(string bindingCollectionName)
        {
            BindingCollectionElement element = null;
            BindingsSection          section = (BindingsSection)ConfigurationManager.GetSection("system.serviceModel/bindings");

            try
            {
                element = section.BindingCollections.Find(new Predicate <BindingCollectionElement>(delegate(BindingCollectionElement target) { return(target.BindingName == "bindingCollectionName"); }));
            }
            catch (KeyNotFoundException)
            {
                throw new ConfigurationErrorsException();
            }
            return(element);
        }
Ejemplo n.º 17
0
        /// <summary>
        /// Applies the current configuration to the WCFMockAdapterBindingCollectionElement
        /// </summary>
        /// <param name="configurationName">The configuration name to be used to configure the adapter binding instance with</param>
        private void ApplyConfiguration(string configurationName)
        {
            BindingsSection bindingsSection = (BindingsSection)System.Configuration.ConfigurationManager.GetSection("system.serviceModel/bindings");
            MockAdapterBindingCollectionElement bindingCollectionElement = (MockAdapterBindingCollectionElement)bindingsSection["mockBinding"];
            MockAdapterBindingElement           element = bindingCollectionElement.Bindings[configurationName];

            if (element != null)
            {
                MockAdapterUtilities.Trace.Trace(
                    System.Diagnostics.TraceEventType.Information,
                    "1007",
                    "Applying binding configuration");

                element.ApplyConfiguration(this);
            }
        }
        private BindingDictionaryValue CreateBindingConfig(Binding binding)
        {
            BindingDictionaryValue value2;

            if (!this.bindingTable.TryGetValue(binding, out value2))
            {
                string str2;
                string name = NamingHelper.GetUniqueName(NamingHelper.CodeName(binding.Name), new NamingHelper.DoesNameExist(this.CheckIfBindingNameInUse), null);
                if (!BindingsSection.TryAdd(name, binding, this.config, out str2))
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(System.ServiceModel.SR.GetString("ConfigBindingCannotBeConfigured"), "endpoint.Binding"));
                }
                value2 = new BindingDictionaryValue(name, str2);
                this.bindingTable.Add(binding, value2);
            }
            return(value2);
        }
Ejemplo n.º 19
0
        internal static HttpBindingCollectionElement GetBindingCollectionElement()
        {
            BindingsSection bindings = AspNetEnvironment.Current.GetConfigurationSection(SectionPath) as BindingsSection;

            if (bindings != null)
            {
                foreach (BindingCollectionElement bindingCollection in bindings.BindingCollections)
                {
                    if (bindingCollection.BindingName == HttpBinding.CollectionElementName)
                    {
                        return(bindingCollection as HttpBindingCollectionElement);
                    }
                }
            }

            return(null);
        }
Ejemplo n.º 20
0
        public void UserConfiguration()
        {
            ServiceModelSectionGroup config = (ServiceModelSectionGroup)ConfigurationManager.OpenExeConfiguration("Test/config/userBinding").GetSectionGroup("system.serviceModel");

            BindingsSection section = config.Bindings;

            BindingCollectionElement collectionElement = section ["userBinding"];

            Assert.AreEqual(typeof(UserBindingCollectionElement), collectionElement.GetType(), "type");

            StandardBindingElementCollection <UserBindingElement> userBindings = ((UserBindingCollectionElement)collectionElement).Bindings;

            Assert.AreEqual(2, userBindings.Count, "Count");

            Assert.AreEqual("UserBinding_1", userBindings [0].Name, "Name_1");
            Assert.AreEqual("UserBinding_2", userBindings [1].Name, "Name_2");
        }
Ejemplo n.º 21
0
        /// <summary>
        /// Initializes a new instance of the DispatcherManager class
        /// </summary>
        /// <param name="bindings">indicating the bindings section</param>
        /// <param name="observer">indicating the observer</param>
        /// <param name="queueFactory">indicating the queue factory</param>
        /// <param name="sharedData">indicating the shared data</param>
        /// <param name="frontendResult">indicating the frontend result</param>
        public DispatcherManager(BindingsSection bindings, SharedData sharedData, BrokerObserver observer, ServiceJobMonitorBase monitor, BrokerQueueFactory queueFactory, ITelepathyContext context)
        {
            this.dispatcherDic          = new Dictionary <string, Dispatcher>();
            this.failedDispatcherList   = new List <string>();
            this.blockedDispatcherDic   = new Dictionary <string, DispatcherInfo>();
            this.blockedDispatcherQueue = new Queue <DispatcherInfo>();

            this.sharedData      = sharedData;
            this.observer        = observer;
            this.monitor         = monitor;
            this.queueFactory    = queueFactory;
            this.context         = context;
            this.defaultCapacity = this.sharedData.ServiceConfig.MaxConcurrentCalls;
            this.blockTimeSpan   = TimeSpan.FromMilliseconds(this.sharedData.Config.LoadBalancing.EndpointNotFoundRetryPeriod);
            this.unblockTimer    = new Timer(new ThreadHelper <object>(new TimerCallback(this.CallbackToQueryBlockedDispatcherList)).CallbackRoot, null, -1, -1);

            this.defaultBinding = BindingHelper.GetBackEndBinding(bindings);
            this.isHttp         = this.defaultBinding.CreateBindingElements().Find <HttpTransportBindingElement>() != null;

            // Update binding's maxMessageSize settings with global maxMessageSize if its enabled (> 0)
            int maxMessageSize = sharedData.ServiceConfig.MaxMessageSize;

            if (maxMessageSize > 0)
            {
                BindingHelper.ApplyMaxMessageSize(this.defaultBinding, maxMessageSize);
            }

            // get soa burst protocol info
            this.httpsBurst = sharedData.BrokerInfo.HttpsBurst;
            if (this.httpsBurst)
            {
                this.azureQueueManager = new AzureQueueManager(sharedData.BrokerInfo.SessionId, this.sharedData.BrokerInfo.ClusterName, this.sharedData.BrokerInfo.ClusterId);
            }

            this.supportsMessageDetails = this.defaultBinding.MessageVersion.Addressing != AddressingVersion.None || this.defaultBinding is BasicHttpBinding;
            BrokerTracing.TraceEvent(TraceEventType.Information, 0, "[DispatcherManager] Init backend binding: OperatiomTimeout = {0}, DefaultCapacity = {1}", this.sharedData.Config.LoadBalancing.ServiceOperationTimeout, this.defaultCapacity);
            BrokerTracing.EtwTrace.LogBackendBindingLoaded(
                sharedData.BrokerInfo.SessionId,
                "Backend",
                maxMessageSize,
                this.defaultBinding.ReceiveTimeout.Ticks,
                this.defaultBinding.SendTimeout.Ticks,
                this.defaultBinding.MessageVersion.ToString(),
                this.defaultBinding.Scheme);
        }
Ejemplo n.º 22
0
        void ApplyConfiguration(string configurationName)
        {
            Configuration            config       = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            ServiceModelSectionGroup sectionGroup = ServiceModelSectionGroup.GetSectionGroup(config);

            BindingsSection bindings = sectionGroup.Bindings;

            NetNamedPipeContextBindingCollectionElement section = (NetNamedPipeContextBindingCollectionElement)bindings[SectionName];
            NetNamedPipeContextBindingElement           element = section.Bindings[configurationName];

            if (element == null)
            {
                throw new ConfigurationErrorsException("There is no binding named " + configurationName + " at " + section.BindingName);
            }
            else
            {
                element.ApplyConfiguration(this);
            }
        }
Ejemplo n.º 23
0
        private void TestAmfBinding()
        {
            try
            {
                Configuration            servicesConfig = WebConfigurationManager.OpenWebConfiguration("~/services");
                ServiceModelSectionGroup serviceModel   = ServiceModelSectionGroup.GetSectionGroup(servicesConfig);
                BindingsSection          bindings       = serviceModel.Bindings;

                CustomBindingElement amfBinding = bindings.CustomBinding.Bindings.Cast <CustomBindingElement>().FirstOrDefault(cb => cb.Name == "amfBinding");
                if (amfBinding == null)
                {
                    MarkAsFail(AmfBindingLabel, "Custom binding with name=\"amfBinding\" not found.", null);
                    return;
                }

                string config       = File.ReadAllText(Server.MapPath("~/Content/swf/config/paths.properties"));
                bool   sfwUsesHttps = config.Replace(" ", string.Empty).Contains("gateway=https:");
                var    http         = amfBinding.FirstOrDefault(x => x is HttpTransportElement);
                var    https        = amfBinding.FirstOrDefault(x => x is HttpsTransportElement);
                if (sfwUsesHttps)
                {
                    if (https == null)
                    {
                        MarkAsFail(AmfBindingLabel, "httpsTransport section not found", "Use <httpsTransport /> within <binding name=\"amfBinding\">  (services/web.config)");
                    }
                }
                else
                {
                    if (http == null)
                    {
                        MarkAsFail(AmfBindingLabel, "httpTransport section not found", "Use <httpTransport /> within <binding name=\"amfBinding\">.  (services/web.config)");
                    }
                }

                MarkAsPass(AmfBindingLabel);
            }
            catch (Exception ex)
            {
                MarkAsFail(AmfBindingLabel, "EXCEPTION DURING TEST: " + ex.Message, null);
            }
        }
Ejemplo n.º 24
0
        BindingDictionaryValue CreateBindingConfig(Binding binding)
        {
            BindingDictionaryValue bindingDV;

            if (!bindingTable.TryGetValue(binding, out bindingDV))
            {
                // [....]: review: Use decoded form to preserve the user-given friendly name, however, beacuse our Encoding algorithm
                // does not touch ASCII names, a name that looks like encoded name will not roundtrip(Example: "_x002C_" will turned into ",")
                string bindingName = NamingHelper.GetUniqueName(NamingHelper.CodeName(binding.Name), this.CheckIfBindingNameInUse, null);
                string bindingSectionName;

                if (!BindingsSection.TryAdd(bindingName, binding, config, out bindingSectionName))
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.GetString(SR.ConfigBindingCannotBeConfigured), "endpoint.Binding"));
                }

                bindingDV = new BindingDictionaryValue(bindingName, bindingSectionName);
                bindingTable.Add(binding, bindingDV);
            }
            return(bindingDV);
        }
Ejemplo n.º 25
0
        private void ApplyConfiguration(string configurationName)
        {
            BindingsSection wcfBindings = (BindingsSection)ConfigurationManager.GetSection("system.serviceModel/bindings");
            // wcfBindings contains system defined bindings and bindingExtensions

            AmqpBindingCollectionElement section = (AmqpBindingCollectionElement)wcfBindings["amqpBinding"];

            if (section == null)
            {
                throw new ConfigurationErrorsException("Missing \"amqpBinding\" configuration section.");
            }

            AmqpBindingConfigurationElement element = section.Bindings[configurationName];

            if (element == null)
            {
                throw new ConfigurationErrorsException(string.Format(System.Globalization.CultureInfo.CurrentCulture,
                                                                     "There is no binding named {0} at {1}.", configurationName, section.BindingName));
            }
            else
            {
                element.ApplyConfiguration(this);
            }
        }
Ejemplo n.º 26
0
        /// <summary>
        /// Load the configuration from the configuration file
        /// If no configuration is found or some part is missing, we will fill the blank with default value
        /// </summary>
        /// <param name="brokerSettings">indicate the broker settings from the session start info, this settings will override the settings load from the configuration file</param>
        /// <param name="brokerInfo">indicating the broker info</param>
        /// <param name="brokerConfig">out the broker configurations</param>
        /// <param name="serviceConfig">out the service configurations</param>
        /// <param name="bindings">output the bindings</param>
        public static void LoadConfiguration(SessionStartInfoContract brokerSettings, BrokerStartInfo brokerInfo, out BrokerConfigurations brokerConfig, out ServiceConfiguration serviceConfig, out BindingsSection bindings)
        {
            // Init config file
            string filename = brokerInfo.ConfigurationFile;

            BrokerTracing.TraceVerbose("[ConfigurationHelper] LoadConfiguration. Step 1: Load configuration file name: {0}", filename);

            brokerConfig  = null;
            serviceConfig = null;
            bindings      = null;

            try
            {
                ExeConfigurationFileMap map = new ExeConfigurationFileMap();
                map.ExeConfigFilename = filename;
                Configuration config = null;
                RetryManager.RetryOnceAsync(
                    () => config = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None),
                    TimeSpan.FromSeconds(1),
                    ex => ex is ConfigurationErrorsException)
                .GetAwaiter()
                .GetResult();
                brokerConfig  = BrokerConfigurations.GetSectionGroup(config);
                serviceConfig = ServiceRegistration.GetSectionGroup(config).Service;
                bindings      = (BindingsSection)config.GetSection(BindingsSectionName);
            }
            catch (ConfigurationErrorsException e)
            {
                ThrowHelper.ThrowSessionFault(SOAFaultCode.ConfigFile_Invalid,
                                              "{0}",
                                              e.ToString());
            }

            if (brokerConfig == null)
            {
                // Set the default value
                brokerConfig = defaultBrokerConfiguration;
                BrokerTracing.TraceEvent(TraceEventType.Information, 0, "[ConfigurationHelper] Didn't find the broker config from the configuration file, use the default configuration");
            }
            else
            {
                // Set the default configuration if the very section is not found
                if (brokerConfig.Monitor == null)
                {
                    brokerConfig.Monitor = defaultBrokerConfiguration.Monitor;
                    BrokerTracing.TraceEvent(TraceEventType.Information, 0, "[ConfigurationHelper] Didn't find the monitor config from the configuration file, use the default configuration");
                }

                if (brokerConfig.Services == null)
                {
                    brokerConfig.Services = defaultBrokerConfiguration.Services;
                    BrokerTracing.TraceEvent(TraceEventType.Information, 0, "[ConfigurationHelper] Didn't find the services config from the configuration file, use the default configuration");
                }

                if (brokerConfig.LoadBalancing == null)
                {
                    brokerConfig.LoadBalancing = defaultBrokerConfiguration.LoadBalancing;
                    BrokerTracing.TraceEvent(TraceEventType.Information, 0, "[ConfigurationHelper] Didn't find the load balancing config from the configuration file, use the default configuration");
                }
            }

            BrokerTracing.TraceVerbose("[ConfigurationHelper] LoadConfiguration. Step 2: Load broker config and service config succeeded.");

            if (brokerConfig.Monitor.AllocationAdjustInterval < MinAllocationAdjustTime && brokerConfig.Monitor.AllocationAdjustInterval != System.Threading.Timeout.Infinite)
            {
                brokerConfig.Monitor.AllocationAdjustInterval = MinAllocationAdjustTime;
            }

            // Update the broker config using the session start info
            if (brokerSettings.ClientIdleTimeout.HasValue)
            {
                brokerConfig.Monitor.ClientIdleTimeout = brokerSettings.ClientIdleTimeout.Value;
                BrokerTracing.TraceEvent(TraceEventType.Verbose, 0, "[ConfigurationHelper] Modified default ClientIdleTimeout to {0}", brokerConfig.Monitor.ClientIdleTimeout);
            }

            if (brokerSettings.ClientConnectionTimeout.HasValue)
            {
                brokerConfig.Monitor.ClientConnectionTimeout = brokerSettings.ClientConnectionTimeout.Value;
                BrokerTracing.TraceEvent(TraceEventType.Verbose, 0, "[ConfigurationHelper] Modified default ClientConnectionTimeout to {0}", brokerConfig.Monitor.ClientConnectionTimeout);
            }

            if (brokerSettings.SessionIdleTimeout.HasValue)
            {
                brokerConfig.Monitor.SessionIdleTimeout = brokerSettings.SessionIdleTimeout.Value;
                BrokerTracing.TraceEvent(TraceEventType.Verbose, 0, "[ConfigurationHelper] Modified default SessionIdleTimeout to {0}", brokerConfig.Monitor.SessionIdleTimeout);
            }

            if (brokerSettings.MessagesThrottleStartThreshold.HasValue)
            {
                brokerConfig.Monitor.MessageThrottleStartThreshold = brokerSettings.MessagesThrottleStartThreshold.Value;
                BrokerTracing.TraceEvent(TraceEventType.Verbose, 0, "[ConfigurationHelper] Modified default MessageThrottleStartThreshold to {0}", brokerConfig.Monitor.MessageThrottleStartThreshold);
            }

            if (brokerSettings.MessagesThrottleStopThreshold.HasValue)
            {
                brokerConfig.Monitor.MessageThrottleStopThreshold = brokerSettings.MessagesThrottleStopThreshold.Value;
                BrokerTracing.TraceEvent(TraceEventType.Verbose, 0, "[ConfigurationHelper] Modified default MessageThrottleStopThreshold to {0}", brokerConfig.Monitor.MessageThrottleStopThreshold);
            }

            if (brokerSettings.ClientBrokerHeartbeatRetryCount.HasValue)
            {
                brokerConfig.Monitor.ClientBrokerHeartbeatRetryCount = brokerSettings.ClientBrokerHeartbeatRetryCount.Value;
                BrokerTracing.TraceEvent(TraceEventType.Verbose, 0, "[ConfigurationHelper] Modified default ClientBrokerHeartbeatRetryCount to {0}", brokerConfig.Monitor.ClientBrokerHeartbeatRetryCount);
            }

            if (brokerSettings.ClientBrokerHeartbeatInterval.HasValue)
            {
                brokerConfig.Monitor.ClientBrokerHeartbeatInterval = brokerSettings.ClientBrokerHeartbeatInterval.Value;
                BrokerTracing.TraceEvent(TraceEventType.Verbose, 0, "[ConfigurationHelper] Modified default ClientBrokerHeartbeatInterval to {0}", brokerConfig.Monitor.ClientBrokerHeartbeatInterval);
            }

            if (brokerSettings.ServiceOperationTimeout.HasValue)
            {
                brokerConfig.LoadBalancing.ServiceOperationTimeout = brokerSettings.ServiceOperationTimeout.Value;
                BrokerTracing.TraceEvent(TraceEventType.Verbose, 0, "[ConfigurationHelper] Modified default ServiceOperationTimeout to {0}", brokerConfig.LoadBalancing.ServiceOperationTimeout);
            }

            if (brokerSettings.DispatcherCapacityInGrowShrink.HasValue)
            {
                brokerConfig.LoadBalancing.DispatcherCapacityInGrowShrink = brokerSettings.DispatcherCapacityInGrowShrink.Value;
                BrokerTracing.TraceEvent(TraceEventType.Verbose, 0, "[ConfigurationHelper] Modified default DispatcherCapacityInGrowShrink to {0}", brokerConfig.LoadBalancing.DispatcherCapacityInGrowShrink);
            }

            if (brokerSettings.MaxMessageSize.HasValue)
            {
                serviceConfig.MaxMessageSize = brokerSettings.MaxMessageSize.Value;
                BrokerTracing.TraceEvent(TraceEventType.Verbose, 0, "[ConfigurationHelper] Modified default MaxMessageSize to {0}", serviceConfig.MaxMessageSize);
            }

            BrokerTracing.TraceVerbose("[ConfigurationHelper] LoadConfiguration. Step 3: Override broker settings using session start info succeeded.");

            // Validate the config section
            string configError;
            bool   validateSucceeded;

            try
            {
                validateSucceeded = brokerConfig.Validate(out configError);
            }
            catch (ConfigurationErrorsException e)
            {
                validateSucceeded = false;
                configError       = e.Message;
            }

            if (!validateSucceeded)
            {
                BrokerTracing.TraceEvent(TraceEventType.Error, 0, "[ConfigurationHelper] Invalid broker configuration section. Error {0}", configError);
                ThrowHelper.ThrowSessionFault(SOAFaultCode.Broker_InvalidConfiguration, configError);
            }

            BrokerTracing.TraceVerbose("[ConfigurationHelper] LoadConfiguration. Step 4: Validate broker configuration succeeded.");

            StringBuilder sb = new StringBuilder();

            sb.AppendLine("[Monitor]");
            BrokerTracing.WriteProperties(sb, brokerConfig.Monitor, 3, typeof(int), typeof(string));
            sb.AppendLine("[BaseAddress]");
            sb.AppendFormat("   Http = {0}\n", brokerConfig.Services.GetBrokerBaseAddress("http"));
            sb.AppendFormat("   Https = {0}\n", brokerConfig.Services.GetBrokerBaseAddress("https"));
            sb.AppendFormat("   NetTcp = {0}\n", brokerConfig.Services.GetBrokerBaseAddress("net.tcp"));
            sb.AppendLine("[LoadBalancing]");
            BrokerTracing.WriteProperties(sb, brokerConfig.LoadBalancing, 3, typeof(int), typeof(string));
            BrokerTracing.TraceVerbose("[ConfigurationHelper] BrokerConfiguration: \n{0}", sb.ToString());
            sb = new StringBuilder();
            sb.AppendLine("[Service]");
            BrokerTracing.WriteProperties(sb, serviceConfig, 3, typeof(int), typeof(string));
            BrokerTracing.TraceVerbose("[ConfigurationHelper] ServiceConfiguration: \n{0}", sb.ToString());
        }
Ejemplo n.º 27
0
        /// <summary>
        /// Build the frontend
        /// </summary>
        /// <param name="sharedData">indicating the shared data</param>
        /// <param name="observer">indicating the broker observer</param>
        /// <param name="clientManager">indicating the client manager</param>
        /// <param name="brokerAuth">indicating the broker authorization</param>
        /// <param name="bindings">indicating the bindings</param>
        /// <param name="azureQueueProxy">indicating the Azure storage proxy</param>
        /// <returns>frontend result</returns>
        public static FrontendResult BuildFrontEnd(SharedData sharedData, BrokerObserver observer, BrokerClientManager clientManager, BrokerAuthorization brokerAuth, BindingsSection bindings, AzureQueueProxy azureQueueProxy)
        {
            FrontendResult result = new FrontendResult();

            // Bug 9514: Do not open frontend for inprocess broker
            if (sharedData.StartInfo.UseInprocessBroker)
            {
                return(result);
            }

            bool flag = false;

            // Open frontend for different scheme

            // TODO: Separate HTTP frontend and Queue frontend
            if (azureQueueProxy != null)
            {
                flag = true;
                result.SetFrontendInfo(BuildHttpFrontend(sharedData, observer, clientManager, brokerAuth, bindings, azureQueueProxy), TransportScheme.Http);
            }
            else
            {
                if ((sharedData.StartInfo.TransportScheme & TransportScheme.Custom) == TransportScheme.Custom)
                {
                    flag = true;
                    result.SetFrontendInfo(BuildCustomFrontend(sharedData, observer, clientManager, brokerAuth, bindings), TransportScheme.Custom);
                }

                if ((sharedData.StartInfo.TransportScheme & TransportScheme.Http) == TransportScheme.Http)
                {
                    flag = true;
                    result.SetFrontendInfo(BuildHttpFrontend(sharedData, observer, clientManager, brokerAuth, bindings, azureQueueProxy), TransportScheme.Http);
                }

                if ((sharedData.StartInfo.TransportScheme & TransportScheme.NetTcp) == TransportScheme.NetTcp)
                {
                    flag = true;
                    result.SetFrontendInfo(BuildNetTcpFrontend(sharedData, observer, clientManager, brokerAuth, bindings), TransportScheme.NetTcp);
                }

                if ((sharedData.StartInfo.TransportScheme & TransportScheme.NetHttp) == TransportScheme.NetHttp)
                {
                    flag = true;
                    result.SetFrontendInfo(BuildNetHttpFrontend(sharedData, observer, clientManager, brokerAuth, bindings), TransportScheme.NetHttp);
                }
            }

            if (!flag)
            {
                BrokerTracing.TraceEvent(TraceEventType.Critical, 0, "[FrontEndBuilder] Invalid transport scheme: {0}", sharedData.StartInfo.TransportScheme);
                ThrowHelper.ThrowSessionFault(SOAFaultCode.Broker_NotSupportedTransportScheme, SR.NotSupportedTransportScheme, sharedData.StartInfo.TransportScheme.ToString());
            }

            return(result);
        }
Ejemplo n.º 28
0
        /// <summary>
        /// Build the custom frontend
        /// </summary>
        /// <param name="sharedData">indicating the shared data</param>
        /// <param name="observer">indicating the broker observer</param>
        /// <param name="clientManager">indicating the client manager</param>
        /// <param name="brokerAuth">indicating the broker authorization</param>
        /// <param name="bindings">indicating the bindings</param>
        /// <returns>frontend info</returns>
        private static FrontendInfo BuildCustomFrontend(SharedData sharedData, BrokerObserver observer, BrokerClientManager clientManager, BrokerAuthorization brokerAuth, BindingsSection bindings)
        {
            FrontendInfo result = new FrontendInfo();

            BrokerTracing.TraceVerbose("[FrontEndBuilder] Start building custom frontend...");

            // Get binding from configuration file
            Binding binding = BindingHelper.GetBinding(TransportScheme.Custom, sharedData.StartInfo.Secure, bindings);

            // Get message size and reader quotas
            BindingElementCollection collection = binding.CreateBindingElements();

            // Sync frontend binding.receiveTimeout with loadBalancing.ServiceOperationTimeout if its enabled (>0)
            int serviceOperationTimeout = sharedData.Config.LoadBalancing.ServiceOperationTimeout;

            if (serviceOperationTimeout > 0)
            {
                binding.SendTimeout = TimeSpan.FromMilliseconds(serviceOperationTimeout);
            }

            // Set frontend binding.ReceiveTimeout to max
            binding.ReceiveTimeout = TimeSpan.MaxValue;

            TransportBindingElement   transportBindingElement = collection.Find <TransportBindingElement>();
            XmlDictionaryReaderQuotas quotas = binding.GetProperty <XmlDictionaryReaderQuotas>(new BindingParameterCollection());

            if (sharedData.ServiceConfig.MaxMessageSize > 0)
            {
                transportBindingElement.MaxReceivedMessageSize = sharedData.Config.LoadBalancing.ServiceOperationTimeout;
                quotas.MaxBytesPerRead        = XmlDictionaryReaderQuotas.Max.MaxBytesPerRead;
                quotas.MaxDepth               = XmlDictionaryReaderQuotas.Max.MaxDepth;
                quotas.MaxNameTableCharCount  = XmlDictionaryReaderQuotas.Max.MaxNameTableCharCount;
                quotas.MaxStringContentLength = Convert.ToInt32(sharedData.ServiceConfig.MaxMessageSize);
                quotas.MaxArrayLength         = Convert.ToInt32(sharedData.ServiceConfig.MaxMessageSize);
            }

            result.MaxMessageSize = transportBindingElement.MaxReceivedMessageSize;
            result.ReaderQuotas   = quotas;

            // Check if the custom binding supports duplex binding
            bool duplex = false;

            if (binding.CanBuildChannelListener <IDuplexSessionChannel>())
            {
                duplex = true;
            }

            StringBuilder sb = new StringBuilder();

            BrokerTracing.WriteProperties(sb, result.ReaderQuotas, 3, typeof(int));
            BrokerTracing.TraceVerbose("[FrontEndBuilder] Build frontend: Step 1: Load binding data:\nMaxMessageSize = {0}\n[ReaderQuotas]\n{1}\nDuplex = {2}", result.MaxMessageSize, sb.ToString(), duplex);

            result.Binding = binding;
            BrokerTracing.EtwTrace.LogFrontendBindingLoaded(
                sharedData.BrokerInfo.SessionId,
                "Custom",
                result.MaxMessageSize,
                binding.ReceiveTimeout.Ticks,
                binding.SendTimeout.Ticks,
                binding.MessageVersion.ToString(),
                binding.Scheme);

            // Generate the net.tcp uri
            Uri baseUri = sharedData.Config.Services.GetBrokerBaseAddress(binding.Scheme);

            if (baseUri == null)
            {
                baseUri = GetDefaultUriByScheme(binding.Scheme);
            }

            BrokerTracing.TraceVerbose("[FrontEndBuilder] Build frontend: Step 2: Load base address: {0}", baseUri);

            Uri brokerUri = ApplySessionId(baseUri, sharedData.BrokerInfo.SessionId, "Custom", sharedData.BrokerInfo.EnableFQDN);

            BrokerTracing.TraceVerbose("[FrontEndBuilder] Build frontend: Step 3: Generate broker uri: {0}", brokerUri);

            // Build the frontend
            if (duplex)
            {
                result.FrontEnd = new DuplexFrontEnd(brokerUri, binding, observer, clientManager, brokerAuth, sharedData);
            }
            else
            {
                if (binding.CanBuildChannelListener <IReplySessionChannel>())
                {
                    result.FrontEnd = new RequestReplyFrontEnd <IReplySessionChannel>(brokerUri, binding, observer, clientManager, brokerAuth, sharedData);
                }
                else if (binding.CanBuildChannelListener <IReplyChannel>())
                {
                    result.FrontEnd = new RequestReplyFrontEnd <IReplyChannel>(brokerUri, binding, observer, clientManager, brokerAuth, sharedData);
                }
                else
                {
                    ThrowHelper.ThrowSessionFault(SOAFaultCode.Broker_BindingNotSupported, SR.BindingNotSupported, binding.Name);
                }
            }

            BrokerTracing.TraceVerbose("[FrontEndBuilder] Build frontend: Step 4: Build broker frontend succeeded.");
            BrokerTracing.EtwTrace.LogFrontendCreated(
                sharedData.BrokerInfo.SessionId,
                "Custom",
                result.FrontEnd.ListenUri);

            Uri controllerUri = ApplySessionId(baseUri, sharedData.BrokerInfo.SessionId, "Custom", sharedData.BrokerInfo.EnableFQDN);

            BrokerTracing.TraceVerbose("[FrontEndBuilder] Build frontend: Step 5: Generate controller base address: {0}", controllerUri);

            result.ControllerFrontend = new ServiceHost(typeof(BrokerController), controllerUri);
            BindingHelper.ApplyDefaultThrottlingBehavior(result.ControllerFrontend);
            ServiceEndpoint controllerEndpoint = result.ControllerFrontend.AddServiceEndpoint(typeof(IController), binding, DefaultControllerPostfix);

            controllerEndpoint.Behaviors.Add(new ControllerFrontendProvider(false, clientManager, brokerAuth, observer, null));
            result.ControllerUri = controllerEndpoint.ListenUri.AbsoluteUri;

            // Check if the binding supports duplex channel
            // If so, create GetResponse frontend
            if (binding.CanBuildChannelListener <IDuplexChannel>() || binding.CanBuildChannelListener <IDuplexSessionChannel>())
            {
                ServiceEndpoint getResponseEndpoint = result.ControllerFrontend.AddServiceEndpoint(typeof(IResponseService), binding, DefaultGetResponsePostfix);
                getResponseEndpoint.Behaviors.Add(new ControllerFrontendProvider(false, clientManager, brokerAuth, observer, null));
                result.GetResponseUri = getResponseEndpoint.ListenUri.AbsoluteUri;
                BrokerTracing.TraceVerbose("[FrontEndBuilder] Build frontend: Step 6: Build controller frontend succeeded: ControllerUri = {0}, GetResponseUri = {1}", result.ControllerUri, result.GetResponseUri);
            }
            else
            {
                BrokerTracing.TraceVerbose("[FrontEndBuilder] Build frontend: Step 6: Build controller frontend succeeded: ControllerUri = {0}", result.ControllerUri);
            }

            BrokerTracing.TraceVerbose("[FrontEndBuilder] Building custom frontend succeeded.");
            BrokerTracing.EtwTrace.LogFrontendControllerCreated(
                sharedData.BrokerInfo.SessionId,
                "Custom",
                result.ControllerUri,
                result.GetResponseUri ?? String.Empty);
            return(result);
        }
Ejemplo n.º 29
0
        /// <summary>
        /// Build the http frontend
        /// </summary>
        /// <param name="sharedData">indicating the shared data</param>
        /// <param name="observer">indicating the broker observer</param>
        /// <param name="clientManager">indicating the client manager</param>
        /// <param name="brokerAuth">indicating the broker authorization</param>
        /// <param name="bindings">indicating the bindings</param>
        /// <returns>frontend info</returns>
        private static FrontendInfo BuildHttpFrontend(SharedData sharedData, BrokerObserver observer, BrokerClientManager clientManager, BrokerAuthorization brokerAuth, BindingsSection bindings, AzureQueueProxy azureQueueProxy)
        {
            FrontendInfo result = new FrontendInfo();

            BrokerTracing.TraceVerbose("[FrontEndBuilder] Start building http frontend...");

            // Get binding from configuration file
            Binding binding = BindingHelper.GetBinding(TransportScheme.Http, sharedData.StartInfo.Secure, bindings);

            // Sync frontend binding.receiveTimeout with loadBalancing.ServiceOperationTimeout if its enabled (>0)
            int serviceOperationTimeout = sharedData.Config.LoadBalancing.ServiceOperationTimeout;

            if (serviceOperationTimeout > 0)
            {
                binding.SendTimeout = TimeSpan.FromMilliseconds(serviceOperationTimeout);
            }

            // Set frontend binding.ReceiveTimeout to max
            binding.ReceiveTimeout = TimeSpan.MaxValue;

            // Get message size and reader quotas
            int maxMessageSize = sharedData.ServiceConfig.MaxMessageSize;

            if (maxMessageSize > 0)
            {
                BindingHelper.ApplyMaxMessageSize(binding, maxMessageSize);
                result.MaxMessageSize = maxMessageSize;
                BrokerTracing.TraceVerbose("[FrontEndBuilder] Build frontend: Step 1: Apply global MaxMessageSize:{0}\n", result.MaxMessageSize);
            }
            else
            {
                BindingElementCollection collection = binding.CreateBindingElements();
                result.MaxMessageSize = collection.Find <TransportBindingElement>().MaxReceivedMessageSize;
                result.ReaderQuotas   = binding.GetProperty <XmlDictionaryReaderQuotas>(new BindingParameterCollection());

                StringBuilder sb = new StringBuilder();
                BrokerTracing.WriteProperties(sb, result.ReaderQuotas, 3, typeof(int));
                BrokerTracing.TraceVerbose("[FrontEndBuilder] Build frontend: Step 1: Load binding data:\nMaxMessageSize = {0}\n[ReaderQuotas]\n{1}", result.MaxMessageSize, sb.ToString());
            }

            result.Binding = binding;
            BrokerTracing.EtwTrace.LogFrontendBindingLoaded(
                sharedData.BrokerInfo.SessionId,
                "Http",
                result.MaxMessageSize,
                binding.ReceiveTimeout.Ticks,
                binding.SendTimeout.Ticks,
                binding.MessageVersion.ToString(),
                binding.Scheme);

            // Generate the http uri
            Uri basehttpUri = sharedData.Config.Services.GetBrokerBaseAddress(sharedData.StartInfo.Secure ? HttpsScheme : HttpScheme);

            if (basehttpUri == null)
            {
                basehttpUri = new Uri(sharedData.StartInfo.Secure ? DefaultHttpsFrontEndServiceUri : DefaultHttpFrontEndServiceUri);
            }

            BrokerTracing.TraceVerbose("[FrontEndBuilder] Build frontend: Step 2: Load base address: {0}", basehttpUri);

            Uri brokerHttpUri = ApplySessionId(basehttpUri, sharedData.BrokerInfo.SessionId, "Http", sharedData.BrokerInfo.EnableFQDN);

            BrokerTracing.TraceVerbose("[FrontEndBuilder] Build frontend: Step 3: Generate broker uri: {0}", brokerHttpUri);

            // Build the frontend
            if (sharedData.StartInfo.UseAzureStorage == true)
            {
                BrokerTracing.TraceVerbose("[FrontEndBuilder] Build frontend: AzureQueueFrontEnd");
                result.FrontEnd = new AzureQueueFrontEnd(azureQueueProxy, brokerHttpUri, observer, clientManager, brokerAuth, sharedData);
            }
            else
            {
                BrokerTracing.TraceVerbose("[FrontEndBuilder] Build frontend: HttpFrontEnd");
                result.FrontEnd = new RequestReplyFrontEnd <IReplyChannel>(brokerHttpUri, binding, observer, clientManager, brokerAuth, sharedData);
                //result.FrontEnd = new OutputInputFrontEnd<IInputChannel>(brokerHttpUri, binding, observer, clientManager, brokerAuth, sharedData);
            }
            BrokerTracing.TraceVerbose("[FrontEndBuilder] Build frontend: Step 4: Build broker frontend succeeded.");
            BrokerTracing.EtwTrace.LogFrontendCreated(
                sharedData.BrokerInfo.SessionId,
                "Http",
                result.FrontEnd.ListenUri);

            Uri controllerHttpUri = ApplySessionId(basehttpUri, sharedData.BrokerInfo.SessionId, "Http", sharedData.BrokerInfo.EnableFQDN);

            BrokerTracing.TraceVerbose("[FrontEndBuilder] Build frontend: Step 5: Generate controller base address: {0}", controllerHttpUri);

            // Bug 3012: Force the http frontend using the singleton instance
            result.ControllerFrontend = new ServiceHost(typeof(BrokerController), controllerHttpUri);
            BindingHelper.ApplyDefaultThrottlingBehavior(result.ControllerFrontend);
            ServiceBehaviorAttribute behavior = result.ControllerFrontend.Description.Behaviors.Find <ServiceBehaviorAttribute>();

            Debug.Assert(behavior != null, "BrokerController must have a behavior.");
            behavior.InstanceContextMode = InstanceContextMode.Single;
            ServiceEndpoint endpoint = result.ControllerFrontend.AddServiceEndpoint(typeof(IController), binding, DefaultControllerPostfix);

            if (sharedData.StartInfo.UseAzureStorage == true)
            {
                endpoint.Behaviors.Add(new ControllerFrontendProvider(true, clientManager, brokerAuth, observer, azureQueueProxy));
            }
            else
            {
                endpoint.Behaviors.Add(new ControllerFrontendProvider(true, clientManager, brokerAuth, observer, null));
            }
            result.ControllerUri = endpoint.ListenUri.AbsoluteUri;
            BrokerTracing.TraceVerbose("[FrontEndBuilder] Build frontend: Step 6: Build controller frontend succeeded: ControllerUri = {0}", result.ControllerUri);

            result.GetResponseUri = null;

            BrokerTracing.TraceVerbose("[FrontEndBuilder] Building http frontend succeeded.");
            BrokerTracing.EtwTrace.LogFrontendControllerCreated(
                sharedData.BrokerInfo.SessionId,
                "Http",
                result.ControllerUri,
                String.Empty);
            return(result);
        }
Ejemplo n.º 30
0
        /// <summary>
        /// Build the NetHttp frontend
        /// </summary>
        /// <param name="sharedData">indicating the shared data</param>
        /// <param name="observer">indicating the broker observer</param>
        /// <param name="clientManager">indicating the client manager</param>
        /// <param name="brokerAuth">indicating the broker authorization</param>
        /// <param name="bindings">indicating the bindings</param>
        /// <returns>frontend info</returns>
        private static FrontendInfo BuildNetHttpFrontend(SharedData sharedData, BrokerObserver observer, BrokerClientManager clientManager, BrokerAuthorization brokerAuth, BindingsSection bindings)
        {
            FrontendInfo result = new FrontendInfo();

            BrokerTracing.TraceVerbose("[FrontEndBuilder] Start building NetHttp frontend...");

            // Get binding from configuration file
            Binding binding = BindingHelper.GetBinding(TransportScheme.NetHttp, sharedData.StartInfo.Secure, bindings);

            // Sync frontend binding.receiveTimeout with loadBalancing.ServiceOperationTimeout if its enabled (>0)
            int serviceOperationTimeout = sharedData.Config.LoadBalancing.ServiceOperationTimeout;

            if (serviceOperationTimeout > 0)
            {
                binding.SendTimeout = TimeSpan.FromMilliseconds(serviceOperationTimeout);
            }

            // Set frontend binding.ReceiveTimeout to max
            binding.ReceiveTimeout = TimeSpan.MaxValue;

            // Update backend binding's maxMessageSize settings with global maxMessageSize if its enabled (> 0)
            int maxMessageSize = sharedData.ServiceConfig.MaxMessageSize;

            if (maxMessageSize > 0)
            {
                BindingHelper.ApplyMaxMessageSize(binding, maxMessageSize);
                result.MaxMessageSize = maxMessageSize;
                BrokerTracing.TraceVerbose("[FrontEndBuilder] Build frontend: Step 1: Apply global MaxMessageSize:{0}\n", result.MaxMessageSize);
            }
            else
            {
                // Get message size and reader quotas
                BindingElementCollection collection = binding.CreateBindingElements();
                result.MaxMessageSize = collection.Find <TransportBindingElement>().MaxReceivedMessageSize;
                result.ReaderQuotas   = binding.GetProperty <XmlDictionaryReaderQuotas>(new BindingParameterCollection());

                StringBuilder sb = new StringBuilder();
                BrokerTracing.WriteProperties(sb, result.ReaderQuotas, 3, typeof(int));
                BrokerTracing.TraceVerbose("[FrontEndBuilder] Build frontend: Step 1: Load binding data:\nMaxMessageSize = {0}\n[ReaderQuotas]\n{1}", result.MaxMessageSize, sb.ToString());
            }

            result.Binding = binding;
            BrokerTracing.EtwTrace.LogFrontendBindingLoaded(
                sharedData.BrokerInfo.SessionId,
                "NetHttp",
                result.MaxMessageSize,
                binding.ReceiveTimeout.Ticks,
                binding.SendTimeout.Ticks,
                binding.MessageVersion.ToString(),
                binding.Scheme);

            // Generate the http uri
            Uri basehttpUri = sharedData.Config.Services.GetBrokerBaseAddress(sharedData.StartInfo.Secure ? HttpsScheme : HttpScheme);

            if (basehttpUri == null)
            {
                basehttpUri = new Uri(sharedData.StartInfo.Secure ? DefaultHttpsFrontEndServiceUri : DefaultHttpFrontEndServiceUri);
            }

            BrokerTracing.TraceVerbose("[FrontEndBuilder] Build frontend: Step 2: Load base address: {0}", basehttpUri);

            Uri brokerNetHttpUri = ApplySessionId(basehttpUri, sharedData.BrokerInfo.SessionId, "NetHttp", sharedData.BrokerInfo.EnableFQDN);

            BrokerTracing.TraceVerbose("[FrontEndBuilder] Build frontend: Step 3: Generate broker uri: {0}", brokerNetHttpUri);

            // Build the frontend
            result.FrontEnd = new DuplexFrontEnd(brokerNetHttpUri, binding, observer, clientManager, brokerAuth, sharedData);
            BrokerTracing.TraceVerbose("[FrontEndBuilder] Build frontend: Step 4: Build broker frontend succeeded.");
            BrokerTracing.EtwTrace.LogFrontendCreated(
                sharedData.BrokerInfo.SessionId,
                "NetHttp",
                result.FrontEnd.ListenUri);

            Uri controllerNetHttpUri = ApplySessionId(basehttpUri, sharedData.BrokerInfo.SessionId, "NetHttp", sharedData.BrokerInfo.EnableFQDN);

            BrokerTracing.TraceVerbose("[FrontEndBuilder] Build frontend: Step 5: Generate controller base address: {0}", controllerNetHttpUri);

            result.ControllerFrontend = new ServiceHost(typeof(BrokerController), controllerNetHttpUri);
            BindingHelper.ApplyDefaultThrottlingBehavior(result.ControllerFrontend);

            ServiceEndpoint controllerEndpoint = result.ControllerFrontend.AddServiceEndpoint(typeof(IController), binding, DefaultControllerPostfix);

            controllerEndpoint.Behaviors.Add(new ControllerFrontendProvider(false, clientManager, brokerAuth, observer, null));
            result.ControllerUri = controllerEndpoint.ListenUri.AbsoluteUri;

            ServiceEndpoint getResponseEndpoint = result.ControllerFrontend.AddServiceEndpoint(typeof(IResponseService), binding, DefaultGetResponsePostfix);

            getResponseEndpoint.Behaviors.Add(new ControllerFrontendProvider(false, clientManager, brokerAuth, observer, null));
            result.GetResponseUri = getResponseEndpoint.ListenUri.AbsoluteUri;

            BrokerTracing.TraceVerbose("[FrontEndBuilder] Build frontend: Step 6: Build controller frontend succeeded: ControllerUri = {0}, GetResponseUri = {1}", result.ControllerUri, result.GetResponseUri);
            BrokerTracing.TraceVerbose("[FrontEndBuilder] Building NetHttp frontend succeeded.");
            BrokerTracing.EtwTrace.LogFrontendControllerCreated(
                sharedData.BrokerInfo.SessionId,
                "NetHttp",
                result.ControllerUri,
                result.GetResponseUri);
            return(result);
        }