Пример #1
0
        /// <summary>
        /// Adds the configured behavior to the selected endpoint
        /// </summary>
        /// <param name="behaviorConfiguration">
        /// </param>
        /// <param name="serviceEndpoint">
        /// </param>
        /// <param name="group">
        /// </param>
        private void AddBehaviors(
            string behaviorConfiguration,
            ServiceEndpoint serviceEndpoint,
            ServiceModelSectionGroup group)
        {
            if (group.Behaviors.EndpointBehaviors.Count == 0)
            {
                return;
            }

            var behaviorElement = group.Behaviors.EndpointBehaviors[behaviorConfiguration];

            for (var i = 0; i < behaviorElement.Count; i++)
            {
                var behaviorExtension = behaviorElement[i];
                var extension         = behaviorExtension.GetType()
                                        .InvokeMember(
                    "CreateBehavior",
                    BindingFlags.InvokeMethod | BindingFlags.NonPublic | BindingFlags.Instance,
                    null,
                    behaviorExtension,
                    null);
                if (extension != null)
                {
                    serviceEndpoint.Behaviors.Add((IEndpointBehavior)extension);
                }
            }
        }
        /// <summary>
        /// Interrogates the app.config file to get a list of WCF client end points that implement the ISIPMonitorPublisher contract.
        /// This is to allow this class to connect to multiple notification servers if needed.
        /// </summary>
        private List <string> GetClientEndPointNames()
        {
            List <string> clientEndPointNames = new List <string>();

            //ServiceModelSectionGroup serviceModelSectionGroup = (ServiceModelSectionGroup)ConfigurationManager.GetSection("system.serviceModel");
            ServiceModelSectionGroup serviceModelSectionGroup = null;

            try
            {
                serviceModelSectionGroup = ServiceModelSectionGroup.GetSectionGroup(ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None));
            }
            catch
            {
                serviceModelSectionGroup = ServiceModelSectionGroup.GetSectionGroup(WebConfigurationManager.OpenWebConfiguration("~"));
            }

            foreach (ChannelEndpointElement client in serviceModelSectionGroup.Client.Endpoints)
            {
                if (client.Contract == CLIENT_CONTRACT && !clientEndPointNames.Contains(client.Name))
                {
                    logger.Debug("MonitorProxyManager found client endpoint for ISIPMonitorPublisher, name=" + client.Name + ".");
                    clientEndPointNames.Add(client.Name);
                }
            }

            return(clientEndPointNames);
        }
Пример #3
0
        public void ServiceEndpointCollection()
        {
            ServiceModelSectionGroup config  = (ServiceModelSectionGroup)ConfigurationManager.OpenExeConfiguration("Test/config/service").GetSectionGroup("system.serviceModel");
            ServiceElement           service = config.Services.Services [1];

            Assert.AreEqual(3, service.Endpoints.Count, "Count");
        }
Пример #4
0
        /// <summary>
        /// Adds the given endpoint unless its already configured in app.config
        /// </summary>
        /// <param name="contractType"></param>
        /// <param name="binding"></param>
        /// <param name="address"></param>
        public void AddDefaultEndpoint(Type contractType, Binding binding, string address)
        {
            var serviceModel = ServiceModelSectionGroup.GetSectionGroup(ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None));

            if (serviceModel == null)
            {
                throw new InvalidOperationException("No service model section found in config");
            }

            bool endpointAlreadyConfigured = false;

            foreach (ServiceElement se in serviceModel.Services.Services)
            {
                if (se.Name == Description.ConfigurationName)
                {
                    foreach (ServiceEndpointElement endpoint in se.Endpoints)
                    {
                        if (endpoint.Contract == contractType.FullName && endpoint.Address.OriginalString == address)
                        {
                            endpointAlreadyConfigured = true;
                        }
                    }
                }
            }
            if (!endpointAlreadyConfigured)
            {
                logger.Debug("Endpoint for contract: " + contractType.Name + " is not found in configuration, going to add it programatically");
                AddServiceEndpoint(contractType, binding, address);
            }
        }
Пример #5
0
        /// <summary>
        /// 更改配置文件
        /// </summary>
        /// <param name="serverIp"></param>
        public void ChangeWCF_URL(string serverIp)
        {
            Configuration             config = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath);
            ConfigurationSectionGroup sct    = config.SectionGroups["system.serviceModel"];
            ServiceModelSectionGroup  serviceModelSectionGroup = sct as ServiceModelSectionGroup;
            ClientSection             clientSection            = serviceModelSectionGroup.Client;

            foreach (ChannelEndpointElement item in clientSection.Endpoints)
            {
                //string[] str = item.Address.ToString().Split('/');
                //string pattern = "";
                //for (int i = 0; i < str.Length - 2; i++)
                //    pattern += str[i] + '/';
                string address = item.Address.ToString();
                //string replacement = string.Format("{0}", serverIp);
                //address = Regex.Replace(address, pattern, replacement);
                address = "http://" + serverIp + ":8732/Design_Time_Addresses/WcfService/Service1/";
                try
                {
                    item.Address = new Uri(address);
                }
                catch (Exception ex)
                {
                    LogFileManager.ObjLog.debug(ex.Message, ex);
                    return;
                }
            }
            config.Save(ConfigurationSaveMode.Modified);
            ConfigurationManager.RefreshSection("system.serviceModel");
        }
        private static ChannelEndpointElement GetEndPointElement(string configurationName)
        {
            var config       = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            var sectionGroup = ServiceModelSectionGroup.GetSectionGroup(config);

            if (sectionGroup == null)
            {
                throw new ConfigurationErrorsException(Resources.GroupExpectedErrorMessage);
            }

            var client       = sectionGroup.Client;
            var contractType = typeof(TService);
            var endPoint     = client.Endpoints.OfType <ChannelEndpointElement>()
                               .FirstOrDefault(ep =>
                                               (ep.Name == configurationName) ||
                                               (ep.Contract == contractType.Name) ||
                                               (ep.Contract == contractType.AssemblyQualifiedName) ||
                                               (ep.Contract == contractType.FullName));

            if (endPoint != null)
            {
                return(endPoint);
            }

            var errorMessage = string.Format(Resources.EndPointMissingErrorMessage,
                                             contractType.AssemblyQualifiedName);

            throw new ConfigurationErrorsException(errorMessage);
        }
Пример #7
0
        protected void EnsureComMetaDataExchangeBehaviorAdded(Configuration config)
        {
            ServiceModelSectionGroup sg = ServiceModelSectionGroup.GetSectionGroup(config);

            if (!sg.Behaviors.ServiceBehaviors.ContainsKey(comServiceBehavior))
            {
                ServiceBehaviorElement behavior = new ServiceBehaviorElement(comServiceBehavior);
                sg.Behaviors.ServiceBehaviors.Add(behavior);
                ServiceMetadataPublishingElement metadataPublishing = new ServiceMetadataPublishingElement();

                if (Tool.Options.Hosting == Hosting.Complus || Tool.Options.Hosting == Hosting.NotSpecified)
                {
                    metadataPublishing.HttpGetEnabled = false;
                }
                else
                {
                    metadataPublishing.HttpGetEnabled = true;
                }
                behavior.Add(metadataPublishing);

                ServiceDebugElement serviceDebug = new ServiceDebugElement();
                serviceDebug.IncludeExceptionDetailInFaults = false;
                behavior.Add(serviceDebug);
            }
        }
Пример #8
0
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        static void Main()
        {
            WebAPIBuilder.BuildWebAPI(ServiceConfiguration.WebAPIUrl);
            WCFHost wcfHost = new WCFHost();

            if (Environment.UserInteractive && Debugger.IsAttached)
            {
                Console.WriteLine("WCFHost running on console mode.");
                Configuration            configuration   = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                ServiceModelSectionGroup serviceModel    = ServiceModelSectionGroup.GetSectionGroup(configuration);
                ServicesSection          servicesSection = serviceModel.Services;

                foreach (ServiceEndpointElement endpoint in servicesSection.Services.Cast <ServiceElement>().Select(s => s.Endpoints).SelectMany(ss => ss.OfType <ServiceEndpointElement>()))
                {
                    Console.WriteLine("Address: {0}", endpoint.Address);
                }

                wcfHost.Start();

                Console.WriteLine("Press any key to stop program...");
                Console.ReadKey();

                wcfHost.Stop();
            }
            else
            {
                ServiceBase.Run(wcfHost);
            }
        }
Пример #9
0
        private void LoadFromFile(string configFilePath)
        {
            var filemap = new ExeConfigurationFileMap()
            {
                ExeConfigFilename = configFilePath
            };
            var config       = ConfigurationManager.OpenMappedExeConfiguration(filemap, ConfigurationUserLevel.None);
            var serviceModel = ServiceModelSectionGroup.GetSectionGroup(config);

            bool loaded = false;

            foreach (ServiceElement se in serviceModel.Services.Services)
            {
                if (!loaded)
                {
                    if (se.Name == this.Description.ConfigurationName)
                    {
                        base.LoadConfigurationSection(se);
                        loaded = true;
                    }
                }
            }
            if (!loaded)
            {
                throw new ArgumentException("ServiceElement doesn't exist");
            }
        }
Пример #10
0
        public void TestInstall_64Bit()
        {
            if (!System.Environment.Is64BitOperatingSystem)
            {
                return;
            }

            Configuration config = Get64bitMachineConfig();

            Assert.IsNotNull(config, "Machine.Config returned null");

            MachineConfigManager.AddMachineConfigurationInfo(
                @"..\..\..\..\Adapter\TransMock.Wcf.Adapter\bin\Debug",
                config);

            config = Get64bitMachineConfig();

            ServiceModelSectionGroup sectionGroup = config.GetSectionGroup("system.serviceModel") as ServiceModelSectionGroup;

            Assert.IsTrue(sectionGroup.Extensions.BindingElementExtensions.ContainsKey("mockTransport"),
                          "The mockBinding element extension is not present in the machine.config");

            Assert.IsTrue(sectionGroup.Extensions.BindingExtensions.ContainsKey("mockBinding"),
                          "The mockBinding extention is not present in the machine.config");
        }
Пример #11
0
        private static T CreateChannel <T>() where T : class
        {
            string key = typeof(T).FullName;
            ServiceEndpointEntity fromCache = CacheHelper.GetFromCache <ServiceEndpointEntity>(key);


            if (fromCache == null)
            {
                Configuration configuration = null;


                configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                ServiceModelSectionGroup smsg = (ServiceModelSectionGroup)configuration.GetSectionGroup("system.serviceModel");

                fromCache = GetEndpointEntity <T>(smsg);
                if (fromCache == null)
                {
                    throw new Exception("Invalid type" + typeof(T));
                }

                SetBindingParam(fromCache.ChannelBinding, smsg);
            }

            CacheHelper.AddToCache(key, fromCache);

            return(CreateChanel <T>(fromCache));
        }
Пример #12
0
        /// <summary>
        /// Create代理
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        private T CreateChannel <T>(int sType) where T : class
        {
            Configuration configuration;

            if (sType == 1)//WinForm
            {
                configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            }
            else//WebForm
            {
                configuration = WebConfigurationManager.OpenWebConfiguration("~");
            }
            ServiceModelSectionGroup smsg = (ServiceModelSectionGroup)configuration.GetSectionGroup("system.serviceModel");


            NetMsmqBinding  netMsmqBinding  = GetBindingByContract <T>(smsg) as NetMsmqBinding;
            EndpointAddress endpointAddress = GetEndpointAddressByContract <T>(smsg);

            if ((netMsmqBinding == null) || (endpointAddress == null))
            {
                throw new ArgumentException("请检查配置!");
            }

            ChannelFactory <T> channelFactory = new ChannelFactory <T>(netMsmqBinding, endpointAddress);
            T basicHttpChannel = channelFactory.CreateChannel();

            return(basicHttpChannel);
        }
Пример #13
0
        public List <string> GetClientNamesFromConfigFile()
        {
            List <string>            ClientNames = null;
            string                   name;
            Configuration            appConfig    = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            ServiceModelSectionGroup serviceModel = ServiceModelSectionGroup.GetSectionGroup(appConfig);
            ClientSection            clients      = serviceModel.Client;

            ChannelEndpointElementCollection cepec = clients.Endpoints;

            if (cepec.Count > 0)
            {
                ClientNames       = new List <string>();
                m_ClientEndPoints = new List <EndPoint>();

                foreach (ChannelEndpointElement cepe in cepec)
                {
                    string[] sa = cepe.Contract.ToString().Split('.');
                    name = sa[0] + "(" + cepe.Binding + ")";


                    m_ClientEndPoints.Add(new EndPoint(cepe.Name, sa[0]));
                    ClientNames.Add(name);
                }
            }

            return(ClientNames);
        }
Пример #14
0
        public override void Install(IDictionary stateSaver)
        {
            base.Install(stateSaver);

            //
            // Create context parameter object.
            //
            InstallerParams options = new InstallerParams(Context);

            options.Save(stateSaver);

            //
            // Load app.config from the installation directory.
            //
            Configuration            config  = ConfigurationManager.OpenExeConfiguration(options.AssemblyPath);
            ServiceModelSectionGroup section = (ServiceModelSectionGroup)config.GetSectionGroup("system.serviceModel");

            //
            // Update all endpoint addresses with the value determined by setup.
            //
            foreach (ChannelEndpointElement endpoint in section.Client.Endpoints)
            {
                SetupLog(string.Format("Updating endpoint address for {0}: URL = {1}", endpoint.Name, options.GetSoapEndpoint()));
                endpoint.Address = new Uri(options.GetSoapEndpoint());
            }

            //
            // Write the modified client configuration back to disk.
            //
            config.Save();
        }
Пример #15
0
        private static string ReadServiceName()
        {
            string _ServiceName = string.Empty;
            var    serviceModel = ServiceModelSectionGroup.GetSectionGroup(ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None));
            var    endpoints    = serviceModel.Services.Services;

            foreach (ServiceElement e in endpoints)
            {
                if (e.Name == "WcfServiceLibrary.ObservableService")
                {
                    foreach (ServiceEndpointElement item in e.Endpoints)
                    {
                        if (item.Name == "PeerEndpoint")
                        {
                            _ServiceName = $"{e.Host.BaseAddresses[0].BaseAddress.ToString()}";
                            var test = new Uri(_ServiceName);
                            _ServiceName = $"{test.Host}:{test.Port}";

                            break;
                        }
                    }
                    break;
                }
            }
            return(_ServiceName);
        }
Пример #16
0
        public static System.ServiceModel.Description.ServiceEndpoint GetServiceEndpoint <T>() where T : IClientChannel
        {
            var configFullName = Assembly.GetExecutingAssembly().Location + ".config";
            var configuration  = ConfigurationManager.OpenMappedExeConfiguration(new ExeConfigurationFileMap {
                ExeConfigFilename = configFullName
            }, ConfigurationUserLevel.None);

            var channelType       = typeof(T);
            var contractType      = channelType.GetInterfaces().First(i => i.Namespace == channelType.Namespace);
            var contractAttribute = contractType.GetCustomAttributes(typeof(ServiceContractAttribute), false).First() as ServiceContractAttribute;

            var serviceModelSectionGroup = ServiceModelSectionGroup.GetSectionGroup(configuration);
            var channelEndpointElement   = serviceModelSectionGroup?.Client.Endpoints.OfType <ChannelEndpointElement>().First(e => e.Contract == contractAttribute?.ConfigurationName);
            var channelFactory           = new ConfigurationChannelFactory <T>(channelEndpointElement.Name, configuration, null);

            //var binding = channelFactory.Endpoint.Binding as BasicHttpBinding;
            //binding.Security.Mode = BasicHttpSecurityMode.TransportCredentialOnly;
            //binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Basic;
            //binding.Security.Transport.ProxyCredentialType = HttpProxyCredentialType.None;

            //binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Basic;
            //binding.Security.Message.ClientCredentialType = BasicHttpMessageCredentialType.UserName;
            //binding.Security.Message.AlgorithmSuite = SecurityAlgorithmSuite.Default;

            //channelFactory.Credentials.UserName.UserName = "******";
            //channelFactory.Credentials.UserName.Password = "";

            return(channelFactory.Endpoint);
        }
Пример #17
0
        private Binding method_0(string string_1, ServiceModelSectionGroup serviceModelSectionGroup_0)
        {
            BindingCollectionElement bindingCollectionElement = serviceModelSectionGroup_0.Bindings[string_1];
            Binding result;

            if (bindingCollectionElement.ConfiguredBindings.Count > 0)
            {
                IBindingConfigurationElement bindingConfigurationElement = bindingCollectionElement.ConfiguredBindings[0];
                Binding binding = this.method_1(bindingConfigurationElement);
                if (bindingConfigurationElement != null)
                {
                    bindingConfigurationElement.ApplyConfiguration(binding);
                }
                if (this.nullable_0.HasValue)
                {
                    binding.CloseTimeout   = this.nullable_0.Value;
                    binding.OpenTimeout    = this.nullable_0.Value;
                    binding.ReceiveTimeout = this.nullable_0.Value;
                    binding.SendTimeout    = this.nullable_0.Value;
                }
                result = binding;
            }
            else
            {
                result = null;
            }
            return(result);
        }
        public void PolicyImporters_DefaultConfiguration()
        {
            ServiceModelSectionGroup        config = OpenConfig("empty");
            PolicyImporterElementCollection col    = config.Client.Metadata.PolicyImporters;

            Type [] types = new Type []
            {
                typeof(CompositeDuplexBindingElementImporter),
                typeof(MessageEncodingBindingElementImporter),
                typeof(OneWayBindingElementImporter),
                typeof(PrivacyNoticeBindingElementImporter),
                typeof(ReliableSessionBindingElementImporter),
                typeof(SecurityBindingElementImporter),
                typeof(TransactionFlowBindingElementImporter),
                typeof(TransportBindingElementImporter),
                typeof(UseManagedPresentationBindingElementImporter)
            };
            foreach (Type type in types)
            {
                PolicyImporterElement item = col [type.AssemblyQualifiedName];
                if (item == null)
                {
                    Assert.Fail(type.Name + " not exists");
                }

                Assert.AreEqual(type.AssemblyQualifiedName, item.Type, type.Name);
            }
        }
Пример #19
0
        public override List <string> GetBaseAddresses(EndpointConfig config)
        {
            List <string> ret = new List <string>();

            Configuration svcconfig = GetConfiguration(true);

            ServiceModelSectionGroup sg          = ServiceModelSectionGroup.GetSectionGroup(svcconfig);
            ServiceElementCollection serviceColl = sg.Services.Services;


            ServiceElement serviceElement = null;

            // Find serviceElement
            foreach (ServiceElement el in serviceColl)
            {
                if (config.MatchServiceType(el.Name))
                {
                    serviceElement = el;
                    break;
                }
            }

            if (null == serviceElement)
            {
                return(ret);
            }

            foreach (BaseAddressElement element in serviceElement.Host.BaseAddresses)
            {
                ret.Add(element.BaseAddress);
            }

            return(ret);
        }
Пример #20
0
        private void StartHost()
        {
            var group =
                ServiceModelSectionGroup.GetSectionGroup(
                    ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None));

            if (group != null)
            {
                //take the first service and endpoint definition
                var service     = group.Services.Services[0];
                var baseAddress =
                    service.Endpoints[0].Address.AbsoluteUri.Replace(service.Endpoints[0].Address.AbsolutePath,
                                                                     String.Empty);
                //create service
                var productService = new ProductService(this);
                //create host
                var host = new ServiceHost(productService, new[] { new Uri(baseAddress) });
                host.AddServiceEndpoint(typeof(IProductService),
                                        new NetNamedPipeBinding(), service.Endpoints[0].Address.AbsolutePath);

                try
                {
                    //open host
                    host.Open();
                }
                catch (CommunicationObjectFaultedException cofe)
                {
                    //log exception
                }
                catch (TimeoutException te)
                {
                    //log exception
                }
            }
        }
Пример #21
0
        public void BindingCollections()
        {
            ServiceModelSectionGroup        g    = GetConfig("Test/config/test1.config");
            List <BindingCollectionElement> coll = g.Bindings.BindingCollections;

            Assert.AreEqual(20, coll.Count, "Count");
        }
Пример #22
0
        private static StandardBindingElement GetBindingElement(string bindingName, string sBindingType, out Type oBindingType)
        {
            oBindingType = null;
            StandardBindingElement bindingElement = null;

            var serviceModel = ServiceModelSectionGroup.GetSectionGroup(_config);

            foreach (var bindingCollection in serviceModel.Bindings.BindingCollections)
            {
                if (bindingCollection.BindingName == sBindingType)
                {
                    foreach (var bindingElem in bindingCollection.ConfiguredBindings)
                    {
                        if (bindingElem.Name == bindingName)
                        {
                            bindingElement = (StandardBindingElement)bindingElem;
                            oBindingType   = bindingCollection.BindingType;
                            break;
                        }
                    }
                }
                if (bindingElement != null)
                {
                    break;
                }
            }
            return(bindingElement);
        }
Пример #23
0
        private static void HostServices()
        {
            EnsureQueueExists();

            List <ServiceHost> lHosts = new List <ServiceHost>();

            try
            {
                Configuration            lAppConfig    = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                ServiceModelSectionGroup lServiceModel = ServiceModelSectionGroup.GetSectionGroup(lAppConfig);

                System.ServiceModel.Configuration.ServicesSection lServices = lServiceModel.Services;
                foreach (ServiceElement lServiceElement in lServices.Services)
                {
                    ServiceHost lHost = new ServiceHost(Type.GetType(GetAssemblyQualifiedServiceName(lServiceElement.Name)));
                    lHost.Open();
                    lHosts.Add(lHost);
                }
                Console.WriteLine("VideoStore Service Started, press Q key to quit");
                while (Console.ReadKey().Key != ConsoleKey.Q)
                {
                    ;
                }
            }
            finally
            {
                foreach (ServiceHost lHost in lHosts)
                {
                    lHost.Close();
                }
            }
        }
Пример #24
0
        public IHttpActionResult GetBindings([FromUri] string bindingType)
        {
            var            serviceModel = ServiceModelSectionGroup.GetSectionGroup(ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None));
            IList <string> result       = serviceModel.Bindings[bindingType].ConfiguredBindings.Select(x => x.Name).ToList();

            return(Ok(result));
        }
Пример #25
0
        CustomBindingCollectionElement OpenConfig()
        {
            ServiceModelSectionGroup config = (ServiceModelSectionGroup)ConfigurationManager.OpenExeConfiguration(TestResourceHelper.GetFullPathOfResource("Test/config/customBinding")).GetSectionGroup("system.serviceModel");

            Assert.AreEqual(7, config.Bindings.CustomBinding.Bindings.Count, "CustomBinding count");
            return(config.Bindings.CustomBinding);
        }
Пример #26
0
        public IHttpActionResult GetBindingTypes()
        {
            var serviceModel = ServiceModelSectionGroup.GetSectionGroup(ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None));
            var types        = serviceModel.Bindings.BindingCollections.Select(x => x.BindingName);

            return(Ok(types));
        }
Пример #27
0
        public void ReadConfiguration()
        {
            ServiceModelSectionGroup config  = (ServiceModelSectionGroup)ConfigurationManager.OpenExeConfiguration("Test/config/service").GetSectionGroup("system.serviceModel");
            ServiceElement           service = config.Services.Services [0];

            Assert.AreEqual("ServiceType", service.Name, "Name");
            Assert.AreEqual("", service.BehaviorConfiguration, "BehaviorConfiguration");
            Assert.AreEqual(3, service.Endpoints.Count, "Endpoints.Count");

            Assert.AreEqual("basicHttp", service.Endpoints [0].Name, "Endpoints [0].Name");
            Assert.AreEqual("basicHttpBinding", service.Endpoints [0].Binding, "Endpoints [0].Binding");
            Assert.AreEqual("HttpServiceContract", service.Endpoints [0].Contract, "Endpoints [0].Contract");
            Assert.AreEqual("/rooted.path", service.Endpoints [0].Address.OriginalString, "Endpoints [0].Address");

            Assert.AreEqual(1, service.Endpoints [0].Headers.Headers.Count, "Endpoints [0].Headers.Headers.Count");
            Assert.AreEqual("Tag", service.Endpoints [0].Headers.Headers [0].Name, "Endpoints [0].Headers.Headers[0].Name");
            Assert.AreEqual("", service.Endpoints [0].Headers.Headers [0].Namespace, "Endpoints [0].Headers.Headers[0].Namespace");

            Assert.AreEqual("", service.Endpoints [1].Name, "Endpoints [1].Name");
            Assert.AreEqual("wsHttpBinding", service.Endpoints [1].Binding, "Endpoints [1].Binding");
            Assert.AreEqual("WSServiceContract", service.Endpoints [1].Contract, "Endpoints [1].Contract");
            Assert.AreEqual("http://other.endpoint.com", service.Endpoints [1].Address.OriginalString, "Endpoints [1].Address");

            Assert.AreEqual("netTcp", service.Endpoints [2].Name, "Endpoints [2].Name");
            Assert.AreEqual("netTcpBinding", service.Endpoints [2].Binding, "Endpoints [2].Binding");
            Assert.AreEqual("TcpServiceContract", service.Endpoints [2].Contract, "Endpoints [2].Contract");
            Assert.AreEqual("path", service.Endpoints [2].Address.OriginalString, "Endpoints [2].Address");

            Assert.AreEqual(new TimeSpan(0, 0, 20), service.Host.Timeouts.CloseTimeout, "Host.Timeouts.CloseTimeout");
            Assert.AreEqual(new TimeSpan(0, 2, 0), service.Host.Timeouts.OpenTimeout, "Host.Timeouts.OpenTimeout");

            Assert.AreEqual(2, service.Host.BaseAddresses.Count, "Host.BaseAddresses.Count");
            Assert.AreEqual("http://endpoint.com/some.path", service.Host.BaseAddresses [0].BaseAddress, "Host.BaseAddresses[0].BaseAddress");
            Assert.AreEqual("net.tcp://endpoint.com", service.Host.BaseAddresses [1].BaseAddress, "Host.BaseAddresses[1].BaseAddress");
        }
        /// <summary>
        /// Method ApplySectionInfo.
        /// </summary>
        /// <param name="serviceFullName">The full name of the type of hosted service.</param>
        /// <param name="serviceModelSectionGroup">ServiceModel section group.</param>
        /// <returns>true if succeeded; otherwise, false.</returns>
        private bool ApplySectionInfo(string serviceFullName, ServiceModelSectionGroup serviceModelSectionGroup)
        {
            if (serviceModelSectionGroup == null)
            {
                return(false);
            }

            if (string.IsNullOrEmpty(serviceFullName))
            {
                return(false);
            }

            bool isElementExist = false;

            foreach (ServiceElement element in serviceModelSectionGroup.Services.Services)
            {
                if (element.Name == serviceFullName)
                {
                    this.LoadConfigurationSection(element);

                    isElementExist = true;

                    break;
                }
            }

            return(isElementExist);
        }
Пример #29
0
        /// <summary>
        /// Retourne l'uri associé au point d'accès principal de l'application.
        ///
        /// Pour les applications, l'uri est de la forme :
        ///   - MACHINE_NAME;http[s]://logical_name:port/[path]/.
        /// </summary>
        /// <returns>Uri du point d'accès principal de l'application.</returns>
        private static string GetEndPointUri()
        {
            if (HttpContext.Current != null)
            {
                return(Environment.MachineName);
            }
            else
            {
                try {
                    System.Configuration.Configuration configuration       = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                    ServiceModelSectionGroup           serviceModelSection = ServiceModelSectionGroup.GetSectionGroup(configuration);
                    if (serviceModelSection != null)
                    {
                        foreach (ServiceElement service in serviceModelSection.Services.Services)
                        {
                            foreach (ServiceEndpointElement sep in service.Endpoints)
                            {
                                if (sep.Address != null)
                                {
                                    return(sep.Address.ToString());
                                }
                            }
                        }
                    }
                } catch (ArgumentException) {
                    return(Environment.MachineName);
                }

                return(Environment.MachineName);
            }
        }
Пример #30
0
        /// <summary>
        /// Gets the system.serviceModel group from the config file
        /// </summary>
        /// <returns></returns>
        private static ServiceModelSectionGroup GetServiceModelSectionGroup()
        {
            ServiceModelSectionGroup svcmod = null;

            try
            {
                AppDomain appDomain = AppDomain.CurrentDomain;
                if (appDomain != null)
                {
                    if (appDomain.SetupInformation.ConfigurationFile.Contains("web.config"))
                    {
                        // Web application
                        var webConfig = WebConfigurationManager.OpenWebConfiguration("~");
                        svcmod = (ServiceModelSectionGroup)webConfig.GetSectionGroup("system.serviceModel");
                    }
                    else
                    {
                        // Stand-alone application
                        Configuration conf = ConfigurationManager.OpenExeConfiguration(Assembly.GetEntryAssembly().Location);
                        svcmod = (ServiceModelSectionGroup)conf.GetSectionGroup("system.serviceModel");
                    }
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.Message, System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Namespace + "." + System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name);
                throw ex;
            }
            return(svcmod);
        }