void AddServiceBehaviors(string configurationName, bool throwIfNotFound) { if (configurationName == null) { return; } ServiceBehaviorElement behavior = ConfigUtil.BehaviorsSection.ServiceBehaviors [configurationName]; if (behavior == null) { if (throwIfNotFound) { throw new ArgumentException(String.Format("Service behavior configuration '{0}' was not found", configurationName)); } return; } KeyedByTypeCollection <IServiceBehavior> behaviors = Description.Behaviors; foreach (var bxe in behavior) { IServiceBehavior b = (IServiceBehavior)bxe.CreateBehavior(); if (behaviors.Contains(b.GetType())) { continue; } behaviors.Add(b); } }
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); } }
public static List <IServiceBehavior> GetDefaultSeviceBehaviors(string scheme) { List <IServiceBehavior> list = new List <IServiceBehavior>(); WCFConfigProvider.InitServiceModel(); if (WCFConfigProvider._serviceModel == null) { return(list); } string defaultServiceBehaviorName = WCFConfigProvider.GetDefaultServiceBehaviorName(scheme); if (WCFConfigProvider._serviceModel.Behaviors.ServiceBehaviors.ContainsKey(defaultServiceBehaviorName)) { ServiceBehaviorElement serviceBehaviorElement = WCFConfigProvider._serviceModel.Behaviors.ServiceBehaviors[defaultServiceBehaviorName]; foreach (BehaviorExtensionElement current in serviceBehaviorElement) { IServiceBehavior serviceBehavior = WCFConfigProvider.CreateBehavior <IServiceBehavior>(current); if (serviceBehavior != null) { list.Add(serviceBehavior); } } } return(list); }
/// <summary> /// Applies the service behavior configuration. /// </summary> /// <param name="serviceHost">The service host.</param> public void ApplyServiceBehaviorConfiguration(ServiceHost serviceHost) { if (_serviceBehaviorElement == null) { lock (SyncLock) { if (_serviceBehaviorElement == null) { var doc = new XmlDocument(); doc.LoadXml(Xml); _customBehaviorElements = FilterCustomBehaviorElements(doc); _serviceBehaviorElement = new ServiceBehaviorElement(); Deserialize(doc.OuterXml, _serviceBehaviorElement); } } } foreach (var item in _serviceBehaviorElement) { SetBehavior(serviceHost.Description.Behaviors, item); } foreach (var item in _customBehaviorElements) { SetBehavior(serviceHost.Description.Behaviors, item); } if (!IsServiceMetadataBehaviorConfigured(serviceHost)) { var smb = new ServiceMetadataBehavior(); serviceHost.Description.Behaviors.Add(smb); } }
protected void EnsureComMetaDataExchangeBehaviorRemoved(Configuration config) { ServiceModelSectionGroup sg = ServiceModelSectionGroup.GetSectionGroup(config); if (sg.Behaviors.ServiceBehaviors.ContainsKey(comServiceBehavior)) { ServiceBehaviorElement element = sg.Behaviors.ServiceBehaviors[comServiceBehavior]; sg.Behaviors.ServiceBehaviors.Remove(element); } }
public static string GetServiceBehaviorElementXml(this IEnumerable <BehaviorExtensionElement> serviceBehaviors) { var serviceBehaviorElement = new ServiceBehaviorElement("ServiceBehavior"); serviceBehaviors.Each(b => serviceBehaviorElement.Add(b)); var configurationProxy = new ConfigurationProxy(); configurationProxy.SetServiceBehaviorElement(serviceBehaviorElement); return(configurationProxy.GetServiceBehaviorElementXml()); }
private static void ApplyServiceBehaviorConfiguration(ServiceHost serviceHost, ServiceConfiguration config) { if (!string.IsNullOrEmpty(config.ServiceBehaviorXML)) { var doc = new XmlDocument(); doc.LoadXml(config.ServiceBehaviorXML); var customBehaviorElements = new List <BehaviorExtensionElement>(); foreach (XmlNode node in doc.FirstChild.ChildNodes) { var customBehaviorTypeDesc = ServiceConfigurationStore.GetCustomBehaviorType(node.Name); if (customBehaviorTypeDesc != null) { var customBehaviorElementType = Type.GetType(customBehaviorTypeDesc.ConfigurationElementTypeClassName); if (customBehaviorElementType == null) { throw new ConfigurationErrorsException( string.Format( "Specified service behavior configuration element type - {0} could not be loaded!", customBehaviorTypeDesc.ConfigurationElementTypeClassName)); } var customBehaviorElement = Activator.CreateInstance(customBehaviorElementType) as BehaviorExtensionElement; if (customBehaviorElement == null) { throw new ConfigurationErrorsException( string.Format( "Specified service behavior configuration element type - {0} could not be initialized!", customBehaviorTypeDesc.ConfigurationElementTypeClassName)); } customBehaviorElement.DeserializeElement(node.OuterXml); customBehaviorElements.Add(customBehaviorElement); node.ParentNode.RemoveChild(node); } } var serviceBehaviorElement = new ServiceBehaviorElement(); serviceBehaviorElement.DeserializeElement(doc.OuterXml); foreach (var item in serviceBehaviorElement) { serviceHost.Description.Behaviors.Add(item.CreateServiceBehavior()); } foreach (var item in customBehaviorElements) { serviceHost.Description.Behaviors.Add(item.CreateServiceBehavior()); } } if (!IsBehaviorConfigured <ServiceMetadataBehavior>(serviceHost)) { var smb = new ServiceMetadataBehavior(); serviceHost.Description.Behaviors.Add(smb); } }
public static void BuildingServiceaBehavior(WCFServiceMeta wCFServiceMeta, ServiceElement serviceElement, SpringServiceHost ssh) { ServiceBehaviorElement sbe = null; if (serviceElement.BehaviorConfiguration != "" && wCFServiceMeta.BehaviorsConfiguration != null) { if (wCFServiceMeta.BehaviorsConfiguration.ServiceBehaviors.ContainsKey(serviceElement.BehaviorConfiguration)) { ServiceBehaviorElementCollection sbec = wCFServiceMeta.BehaviorsConfiguration.ServiceBehaviors; foreach (ServiceBehaviorElement o in sbec) { if (o.Name == serviceElement.BehaviorConfiguration) { sbe = o; break; } } if (sbe != null) { //ServiceBehavior smb = new ServiceMetadataBehavior(); foreach (var metadata in sbe) { switch (metadata.GetType().FullName) { case "System.ServiceModel.Configuration.DataContractSerializerElement": { DataContractSerializerElement dse = metadata as DataContractSerializerElement; if (dse != null) { int i = dse.MaxItemsInObjectGraph; ContractDescription cd = ssh.Description.Endpoints.FirstOrDefault(o => o.Name != "IMetadataExchange").Contract; OperationDescriptionCollection opdc = cd.Operations; foreach (OperationDescription odp in opdc) { DataContractSerializerOperationBehavior dsb = new DataContractSerializerOperationBehavior(odp); dsb.IgnoreExtensionDataObject = dse.IgnoreExtensionDataObject; dsb.MaxItemsInObjectGraph = dse.MaxItemsInObjectGraph; odp.Behaviors.Remove <DataContractSerializerOperationBehavior>(); odp.Behaviors.Add(dsb); } return; } break; } } } } } } }
private static void AddServiceBehavior(ServiceHost serviceHost, string behavior) { var doc = new XmlDocument(); doc.LoadXml(behavior); var serviceBehaviorElement = new ServiceBehaviorElement(); ConfigHelper.Deserialize(doc.OuterXml, serviceBehaviorElement); foreach (var item in serviceBehaviorElement) { ConfigHelper.SetBehavior(serviceHost.Description.Behaviors, item); } }
public void ServiceTimeoutsElement() { ServiceBehaviorElement behavior = OpenConfig(); ServiceTimeoutsElement element = (ServiceTimeoutsElement)behavior [typeof(ServiceTimeoutsElement)]; if (element == null) { Assert.Fail("ServiceTimeoutsElement is not exist in collection."); } Assert.AreEqual("System.ServiceModel.Description.ServiceTimeoutsBehavior", element.BehaviorType.FullName, "BehaviorType"); Assert.AreEqual("serviceTimeouts", element.ConfigurationElementName, "ConfigurationElementName"); Assert.AreEqual(new TimeSpan(0, 3, 0), element.TransactionTimeout, "TransactionTimeout"); }
public void DataContractSerializerElement() { ServiceBehaviorElement behavior = OpenConfig(); DataContractSerializerElement element = (DataContractSerializerElement)behavior [typeof(DataContractSerializerElement)]; if (element == null) { Assert.Fail("DataContractSerializerElement is not exist in collection."); } Assert.AreEqual("System.ServiceModel.Dispatcher.DataContractSerializerServiceBehavior", element.BehaviorType.FullName, "BehaviorType"); Assert.AreEqual("dataContractSerializer", element.ConfigurationElementName, "ConfigurationElementName"); Assert.AreEqual(true, element.IgnoreExtensionDataObject, "IgnoreExtensionDataObject"); Assert.AreEqual(32768, element.MaxItemsInObjectGraph, "MaxItemsInObjectGraph"); }
public void ServiceThrottlingElement() { ServiceBehaviorElement behavior = OpenConfig(); ServiceThrottlingElement element = (ServiceThrottlingElement)behavior [typeof(ServiceThrottlingElement)]; if (element == null) { Assert.Fail("ServiceThrottlingElement is not exist in collection."); } Assert.AreEqual(typeof(ServiceThrottlingBehavior), element.BehaviorType, "BehaviorType"); Assert.AreEqual("serviceThrottling", element.ConfigurationElementName, "ConfigurationElementName"); Assert.AreEqual(32, element.MaxConcurrentCalls, "MaxConcurrentCalls"); Assert.AreEqual(20, element.MaxConcurrentSessions, "MaxConcurrentSessions"); Assert.AreEqual(14, element.MaxConcurrentInstances, "MaxConcurrentInstances"); }
static ServiceDescription CreateDescription(Type serviceType) { ServiceDescription description = new ServiceDescription(); //添加以特性方式应用的服务行为 description.ServiceType = serviceType; var behaviors = (from attribute in serviceType.GetCustomAttributes(false) where attribute is IServiceBehavior select(IServiceBehavior) attribute).ToArray(); Array.ForEach <IServiceBehavior>(behaviors, behavior => description.Behaviors.Add(behavior)); //确保服务具有一个ServiceBehaviorAttribute行为 ServiceBehaviorAttribute serviceBehaviorAttribute = description.Behaviors.Find <ServiceBehaviorAttribute>(); if (null == serviceBehaviorAttribute) { serviceBehaviorAttribute = new ServiceBehaviorAttribute(); description.Behaviors.Add(serviceBehaviorAttribute); } //初始化Name、Namespace和ConfigurationName description.Name = serviceBehaviorAttribute.Name ?? serviceType.Name; description.Namespace = serviceBehaviorAttribute.Namespace ?? "http://tempuri.org/"; description.ConfigurationName = serviceBehaviorAttribute.ConfigurationName ?? serviceType.Namespace + "." + serviceType.Name; //添加以配置方式应用的服务行为 ServiceElement serviceElement = ConfigLoader.GetServiceElement(description.ConfigurationName); if (!string.IsNullOrEmpty(serviceElement.BehaviorConfiguration)) { ServiceBehaviorElement behaviorElement = ConfigLoader.GetServiceBehaviorElement(serviceElement.BehaviorConfiguration); foreach (BehaviorExtensionElement extensionElement in behaviorElement) { IServiceBehavior serviceBehavior = (IServiceBehavior)extensionElement.CreateBehavior(); description.Behaviors.Add(serviceBehavior); } } //添加配置的终结点 foreach (ServiceEndpointElement endpointElement in serviceElement.Endpoints) { description.Endpoints.Add(CreateServiceEndpoint(serviceType, endpointElement)); } return(description); }
public void ServiceSecurityAuditElement() { ServiceBehaviorElement behavior = OpenConfig(); ServiceSecurityAuditElement element = (ServiceSecurityAuditElement)behavior [typeof(ServiceSecurityAuditElement)]; if (element == null) { Assert.Fail("ServiceSecurityAuditElement is not exist in collection."); } Assert.AreEqual(typeof(ServiceSecurityAuditBehavior), element.BehaviorType, "BehaviorType"); Assert.AreEqual("serviceSecurityAudit", element.ConfigurationElementName, "ConfigurationElementName"); Assert.AreEqual(AuditLogLocation.Application, element.AuditLogLocation, "AuditLogLocation"); Assert.AreEqual(false, element.SuppressAuditFailure, "SuppressAuditFailure"); Assert.AreEqual(AuditLevel.Success, element.ServiceAuthorizationAuditLevel, "ServiceAuthorizationAuditLevel"); Assert.AreEqual(AuditLevel.Success, element.MessageAuthenticationAuditLevel, "MessageAuthenticationAuditLevel"); }
private static ServiceDescription CreateDescription(Type serviceType) { ServiceDescription description = new ServiceDescription(); description.ServiceType = serviceType; var behaivors = (from attribute in serviceType.GetCustomAttributes(false) where attribute is IServiceBehavior select(IServiceBehavior) attribute).ToArray(); Array.ForEach <IServiceBehavior>(behaivors, behaivor => description.Behaviors.Add(behaivor)); ServiceBehaviorAttribute serviceBehaviorAttribute = description.Behaviors.Find <ServiceBehaviorAttribute>(); if (null == serviceBehaviorAttribute) { serviceBehaviorAttribute = new ServiceBehaviorAttribute(); description.Behaviors.Add(serviceBehaviorAttribute); } description.Name = serviceBehaviorAttribute.Name ?? serviceType.Name; description.Namespace = serviceBehaviorAttribute.Namespace ?? "http://www.tempri.org"; description.ConfigurationName = serviceBehaviorAttribute.ConfigurationName ?? description.Namespace + "." + description.Name; //添加服务行为 ServiceElement serviceElement = ConfigLoader.GetServiceElement(description.ConfigurationName); if (!string.IsNullOrEmpty(serviceElement.BehaviorConfiguration)) { ServiceBehaviorElement behaviorElement = ConfigLoader.GetServiceBehaviorElement(serviceElement.BehaviorConfiguration); foreach (BehaviorExtensionElement item in behaviorElement) { IServiceBehavior serviceBehavior = item.CreateBehavior() as IServiceBehavior; description.Behaviors.Add(serviceBehavior); } } foreach (ServiceEndpointElement item in serviceElement.Endpoints) { description.Endpoints.Add(CreateServiceEndpoint(serviceType, item)); } return(description); }
private static void AddServiceBehavior(ServiceHost serviceHost, string behavior) { try { var doc = new XmlDocument(); doc.LoadXml(behavior); var serviceBehaviorElement = new ServiceBehaviorElement(); ConfigHelper.Deserialize(doc.OuterXml, serviceBehaviorElement); foreach (var item in serviceBehaviorElement) { ConfigHelper.SetBehavior(serviceHost.Description.Behaviors, item); } } catch (Exception ex) { ex.Handle(WcfLogProvider.ModuleName, "WcfServiceHostFactory", "AddServiceBehavior"); throw; } }
public void ServiceDebugElement() { ServiceBehaviorElement behavior = OpenConfig(); ServiceDebugElement element = (ServiceDebugElement)behavior [typeof(ServiceDebugElement)]; if (element == null) { Assert.Fail("ServiceDebugElement is not exist in collection."); } Assert.AreEqual(typeof(ServiceDebugBehavior), element.BehaviorType, "BehaviorType"); Assert.AreEqual("serviceDebug", element.ConfigurationElementName, "ConfigurationElementName"); Assert.AreEqual(false, element.HttpHelpPageEnabled, "HttpHelpPageEnabled"); Assert.AreEqual("http://help.page.url", element.HttpHelpPageUrl.OriginalString, "HttpHelpPageUrl"); Assert.AreEqual(false, element.HttpsHelpPageEnabled, "HttpsHelpPageEnabled"); Assert.AreEqual("https://help.page.url", element.HttpsHelpPageUrl.OriginalString, "HttpsHelpPageUrl"); Assert.AreEqual(true, element.IncludeExceptionDetailInFaults, "IncludeExceptionDetailInFaults"); }
public void ServiceMetadataPublishingElement() { ServiceBehaviorElement behavior = OpenConfig(); ServiceMetadataPublishingElement element = (ServiceMetadataPublishingElement)behavior [typeof(ServiceMetadataPublishingElement)]; if (element == null) { Assert.Fail("ServiceMetadataPublishingElement is not exist in collection."); } Assert.AreEqual(typeof(ServiceMetadataBehavior), element.BehaviorType, "BehaviorType"); Assert.AreEqual("serviceMetadata", element.ConfigurationElementName, "ConfigurationElementName"); Assert.AreEqual(true, element.HttpGetEnabled, "HttpGetEnabled"); Assert.AreEqual("http://get.url", element.HttpGetUrl.OriginalString, "HttpGetUrl"); Assert.AreEqual(true, element.HttpsGetEnabled, "HttpsGetEnabled"); Assert.AreEqual("https://get.url", element.HttpsGetUrl.OriginalString, "HttpsHelpPageUrl"); Assert.AreEqual("http://external.metadata.location", element.ExternalMetadataLocation.OriginalString, "ExternalMetadataLocation"); Assert.AreEqual(PolicyVersion.Policy12, element.PolicyVersion, "PolicyVersion"); }
public void ServiceAuthorizationElement() { ServiceBehaviorElement behavior = OpenConfig(); ServiceAuthorizationElement serviceAuthorization = (ServiceAuthorizationElement)behavior [typeof(ServiceAuthorizationElement)]; if (serviceAuthorization == null) { Assert.Fail("ServiceAuthorizationElement is not exist in collection."); } Assert.AreEqual(typeof(ServiceAuthorizationBehavior), serviceAuthorization.BehaviorType, "BehaviorType"); Assert.AreEqual("serviceAuthorization", serviceAuthorization.ConfigurationElementName, "ConfigurationElementName"); Assert.AreEqual("RoleProvider", serviceAuthorization.RoleProviderName, "RoleProviderName"); Assert.AreEqual(PrincipalPermissionMode.UseAspNetRoles, serviceAuthorization.PrincipalPermissionMode, "PrincipalPermissionMode"); Assert.AreEqual(true, serviceAuthorization.ImpersonateCallerForAllOperations, "ImpersonateCallerForAllOperations"); Assert.AreEqual("SerAuthManagType", serviceAuthorization.ServiceAuthorizationManagerType, "ServiceAuthorizationManagerType"); Assert.AreEqual(2, serviceAuthorization.AuthorizationPolicies.Count, "AuthorizationPolicies.Count"); Assert.AreEqual("PolicyType1", serviceAuthorization.AuthorizationPolicies [0].PolicyType, "AuthorizationPolicies[0].PolicyType"); Assert.AreEqual("PolicyType2", serviceAuthorization.AuthorizationPolicies [1].PolicyType, "AuthorizationPolicies[1].PolicyType"); }
/// <summary> /// This method adds the neccessary configuration elements to hook up /// Thinktecture.ServiceModel.Extensions.Metdata extension to service the /// service code being generated. /// </summary> private void AddMetadataServiceBehavior() { // Get a pointer to system.serviceModel section. ConfigurationSectionGroup csg = configuration.SectionGroups["system.serviceModel"]; // Notify if we get a null reference. Debug.Assert(csg != null, "system.serviceModel section could not be found in the configuration."); if (csg != null) { // Try to find the extensions element. ExtensionsSection extensionsSection = csg.Sections["extensions"] as ExtensionsSection; // Create it if it wasn't found. if (extensionsSection == null) { extensionsSection = new ExtensionsSection(); csg.Sections.Add("extensions", extensionsSection); } // Now create the new behavior extension. ExtensionElement metadataServiceExtensionElement = new ExtensionElement(); metadataServiceExtensionElement.Name = "metadataService"; //TODO: Make this more dynamic so it can discover the assembly version etc otherwise this will always throw exceptions // that the behavior extension was not found in the collection. metadataServiceExtensionElement.Type = "Thinktecture.ServiceModel.Extensions.Metadata.StaticMetadataBehaviorElement, Thinktecture.ServiceModel.Extensions.Metadata, Version=1.1.0.0, Culture=neutral, PublicKeyToken=20fb7cabbfb92df4"; // Add the newly created behavior extension to the extensions section. extensionsSection.BehaviorExtensions.Add(metadataServiceExtensionElement); // Try to find the behaviors element. BehaviorsSection behaviorsSection = csg.Sections["behaviors"] as BehaviorsSection; // Create it if it wasn't found. if (behaviorsSection == null) { behaviorsSection = new BehaviorsSection(); csg.Sections.Add("behaviors", behaviorsSection); } // Add the new service behavior. ServiceBehaviorElement serviceBehavior = new ServiceBehaviorElement(); serviceBehavior.Name = "metadataServiceExtension"; behaviorsSection.ServiceBehaviors.Add(serviceBehavior); StaticMetadataBehaviorElement behaviorExtensionElement = new StaticMetadataBehaviorElement(); behaviorExtensionElement.RootMetadataFileLocation = options.MetadataLocation; behaviorExtensionElement.MetadataUrl = "wsdl"; serviceBehavior.Add(behaviorExtensionElement); // Find the service section. ServicesSection servicesSection = csg.Sections["services"] as ServicesSection; if (servicesSection != null) { string fqServiceTypeName = GetFullyQulifiedTypeName(GetServiceTypeName()); ServiceElement serviceElement = servicesSection.Services[fqServiceTypeName] as ServiceElement; if (serviceElement != null) { serviceElement.BehaviorConfiguration = "metadataServiceExtension"; } } } }
protected virtual void ApplyConfiguration() { if (Description == null) { throw new InvalidOperationException("ApplyConfiguration requires that the Description property be initialized. Either provide a valid ServiceDescription in the CreateDescription method or override the ApplyConfiguration method to provide an alternative implementation"); } ServiceElement service = GetServiceElement(); //TODO: Should we call here LoadServiceElement ? if (service != null) { //base addresses HostElement host = service.Host; foreach (BaseAddressElement baseAddress in host.BaseAddresses) { AddBaseAddress(new Uri(baseAddress.BaseAddress)); } // behaviors // TODO: use EvaluationContext of ServiceElement. ServiceBehaviorElement behavior = ConfigUtil.BehaviorsSection.ServiceBehaviors [service.BehaviorConfiguration]; if (behavior != null) { foreach (var bxe in behavior) { IServiceBehavior b = (IServiceBehavior)bxe.CreateBehavior(); Description.Behaviors.Add(b); } } // services foreach (ServiceEndpointElement endpoint in service.Endpoints) { // FIXME: consider BindingName as well ServiceEndpoint se = AddServiceEndpoint( endpoint.Contract, ConfigUtil.CreateBinding(endpoint.Binding, endpoint.BindingConfiguration), endpoint.Address.ToString()); // endpoint behaviors EndpointBehaviorElement epbehavior = ConfigUtil.BehaviorsSection.EndpointBehaviors [endpoint.BehaviorConfiguration]; if (epbehavior != null) { foreach (var bxe in epbehavior) { IEndpointBehavior b = (IEndpointBehavior)bxe.CreateBehavior(); se.Behaviors.Add(b); } } } } // TODO: consider commonBehaviors here // ensure ServiceAuthorizationBehavior Authorization = Description.Behaviors.Find <ServiceAuthorizationBehavior> (); if (Authorization == null) { Authorization = new ServiceAuthorizationBehavior(); Description.Behaviors.Add(Authorization); } // ensure ServiceDebugBehavior ServiceDebugBehavior debugBehavior = Description.Behaviors.Find <ServiceDebugBehavior> (); if (debugBehavior == null) { debugBehavior = new ServiceDebugBehavior(); Description.Behaviors.Add(debugBehavior); } }
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); } }
/// <summary> /// 获取启动服务参数 /// </summary> /// <param name="implementsContractType">实体契约类的类型</param> /// <param name="interfaceContractType">契约类型</param> /// <param name="uri">服务地址</param> /// <param name="binding">启动服务类型</param> public void GetServiceConfig(Type implementsContractType, Type interfaceContractType, Uri uri, BindingType binding) { ImplementsContractType = implementsContractType; AddService(implementsContractType.ToString()); ServiceEndpointElement item = new ServiceEndpointElement(uri, interfaceContractType.ToString()); item.BindingConfiguration = item.Name = interfaceContractType.ToString(); item.Binding = binding.ToString(); ServiceElement service = serviceconfig.Services[implementsContractType.ToString()]; service.Endpoints.Add(item); SetBindingParam(uri, binding, item.BindingConfiguration); if (!behaviorconfig.ServiceBehaviors.ContainsKey(service.BehaviorConfiguration)) { ServiceBehaviorElement haviorelement = new ServiceBehaviorElement();// _setting.BehaviorConfig.ServiceBehaviors[service.BehaviorConfiguration]; haviorelement.Name = service.BehaviorConfiguration; #region 并发设置 //List<ServiceThrottlingElement> throttlingConfig = haviorelement.OfType<ServiceThrottlingElement>().ToList(); ServiceThrottlingElement throttlingBehavior = new ServiceThrottlingElement();// host.Description.Behaviors.Find<ServiceThrottlingBehavior>(); //当前ServiceHost能够处理的最大并发消息数量,默认值为16 throttlingBehavior.MaxConcurrentCalls = int.MaxValue; //当前ServiceHost允许存在的InstanceContext的最大数量,默认值为26 throttlingBehavior.MaxConcurrentInstances = int.MaxValue; //当前ServiceHost允许的最大并发会话数量,默认值为10 throttlingBehavior.MaxConcurrentSessions = int.MaxValue; //throttlingConfig.Add(throttlingBehavior); haviorelement.Add(throttlingBehavior); #endregion #region 序列化最大项 DataContractSerializerElement dataContractSerializerElement = new System.ServiceModel.Configuration.DataContractSerializerElement(); dataContractSerializerElement.MaxItemsInObjectGraph = 2147483647; haviorelement.Add(dataContractSerializerElement); #endregion #region 是否充许客户端看到详细错误信息 ServiceDebugElement debugConfig = new ServiceDebugElement(); debugConfig.IncludeExceptionDetailInFaults = _isShowErrorInfoToClient; haviorelement.Add(debugConfig); #endregion behaviorconfig.ServiceBehaviors.Add(haviorelement); } }
/// <summary> /// This method adds the neccessary configuration elements to hook up /// Thinktecture.ServiceModel.Extensions.Metdata extension to service the /// service code being generated. /// </summary> private void AddMetadataServiceBehavior() { // Get a pointer to system.serviceModel section. ConfigurationSectionGroup csg = configuration.SectionGroups["system.serviceModel"]; // Notify if we get a null reference. Debug.Assert(csg != null, "system.serviceModel section could not be found in the configuration."); if (csg != null) { // Try to find the extensions element. ExtensionsSection extensionsSection = csg.Sections["extensions"] as ExtensionsSection; // Create it if it wasn't found. if (extensionsSection == null) { extensionsSection = new ExtensionsSection(); csg.Sections.Add("extensions", extensionsSection); } // Now create the new behavior extension. ExtensionElement metadataServiceExtensionElement = new ExtensionElement(); metadataServiceExtensionElement.Name = "metadataService"; //TODO: Make this more dynamic so it can discover the assembly version etc otherwise this will always throw exceptions // that the behavior extension was not found in the collection. metadataServiceExtensionElement.Type = "Thinktecture.ServiceModel.Extensions.Metadata.StaticMetadataBehaviorElement, Thinktecture.ServiceModel.Extensions.Metadata, Version=1.0.14.0, Culture=neutral, PublicKeyToken=20fb7cabbfb92df4"; // Add the newly created behavior extension to the extensions section. extensionsSection.BehaviorExtensions.Add(metadataServiceExtensionElement); // Try to find the behaviors element. BehaviorsSection behaviorsSection = csg.Sections["behaviors"] as BehaviorsSection; // Create it if it wasn't found. if (behaviorsSection == null) { behaviorsSection = new BehaviorsSection(); csg.Sections.Add("behaviors", behaviorsSection); } // Add the new service behavior. ServiceBehaviorElement serviceBehavior = new ServiceBehaviorElement(); serviceBehavior.Name = "metadataServiceExtension"; behaviorsSection.ServiceBehaviors.Add(serviceBehavior); StaticMetadataBehaviorElement behaviorExtensionElement = new StaticMetadataBehaviorElement(); behaviorExtensionElement.RootMetadataFileLocation = options.MetadataLocation; behaviorExtensionElement.MetadataUrl = "wsdl"; serviceBehavior.Add(behaviorExtensionElement); // Find the service section. ServicesSection servicesSection = csg.Sections["services"] as ServicesSection; if (servicesSection != null) { string fqServiceTypeName = GetFullyQulifiedTypeName(GetServiceTypeName()); ServiceElement serviceElement = servicesSection.Services[fqServiceTypeName] as ServiceElement; if (serviceElement != null) { serviceElement.BehaviorConfiguration = "metadataServiceExtension"; } } } }
public CodeGenerationResults Generate(IArtifactLink link) { CodeGenerationResults result = new CodeGenerationResults(); string serviceImplementationName = string.Empty; string serviceContractName = string.Empty; string serviceNamespace = string.Empty; const string behavior = "_Behavior"; if (link is IModelReference) { this.serviceProvider = Utility.GetData <IServiceProvider>(link); ProjectNode project = Utility.GetData <ProjectNode>(link); ServiceDescription serviceDescription = ((IModelReference)link).ModelElement as ServiceDescription; Configuration configuration = GetConfiguration(link, project); // abort if we got errors in config file if (configuration == null) { return(result); } try { ServiceReference serviceReference = (ServiceReference)serviceDescription; SCModel.Service service = GetMelReference <SCModel.Service>(serviceReference.ServiceImplementationType); serviceImplementationName = ResolveTypeReference(service); serviceContractName = GetServiceContractName(service.ServiceContract); serviceNamespace = service.ServiceContract.Namespace; ServiceModelConfigurationManager manager = new ServiceModelConfigurationManager(configuration); ServiceElement serviceElement = new ServiceElement(); serviceElement.Name = serviceImplementationName; serviceElement.BehaviorConfiguration = string.Concat(serviceImplementationName, behavior); foreach (Endpoint endpoint in serviceDescription.Endpoints) { ServiceEndpointElement endpointElement = new ServiceEndpointElement(); endpointElement.Name = endpoint.Name; endpointElement.Contract = serviceContractName; endpointElement.Binding = ((WcfEndpoint)endpoint.ObjectExtender).BindingType.ToString(); endpointElement.Address = new Uri(endpoint.Address ?? string.Empty, UriKind.RelativeOrAbsolute); endpointElement.BindingNamespace = serviceNamespace; serviceElement.Endpoints.Add(endpointElement); } manager.UpdateService(serviceElement); ServiceBehaviorElement behaviorElement = new ServiceBehaviorElement(); behaviorElement.Name = string.Concat(serviceImplementationName, behavior); ServiceDebugElement debugElement = new ServiceDebugElement(); debugElement.IncludeExceptionDetailInFaults = false; behaviorElement.Add(debugElement); if (((WcfServiceDescription)serviceDescription.ObjectExtender).EnableMetadataPublishing) { ServiceMetadataPublishingElement metadataPublishingElement = new ServiceMetadataPublishingElement(); metadataPublishingElement.HttpGetEnabled = true; behaviorElement.Add(metadataPublishingElement); ServiceEndpointElement mexEndpointElement = ServiceModelConfigurationManager.GetMetadataExchangeEndpoint(); serviceElement.Endpoints.Add(mexEndpointElement); } manager.UpdateBehavior(behaviorElement); manager.Save(); result.Add(link.ItemPath, File.ReadAllText(configuration.FilePath)); } finally { if (configuration != null && File.Exists(configuration.FilePath)) { File.Delete(configuration.FilePath); } } } return(result); }
public void ServiceCredentialsElement() { ServiceBehaviorElement behavior = OpenConfig(); ServiceCredentialsElement element = (ServiceCredentialsElement)behavior [typeof(ServiceCredentialsElement)]; if (element == null) { Assert.Fail("ServiceCredentialsElement is not exist in collection."); } Assert.AreEqual(typeof(ServiceCredentials), element.BehaviorType, "BehaviorType"); Assert.AreEqual("serviceCredentials", element.ConfigurationElementName, "ConfigurationElementName"); Assert.AreEqual("ServiceCredentialsType", element.Type, "Type"); Assert.AreEqual("FindValue", element.ClientCertificate.Certificate.FindValue, "ClientCertificate.Certificate.FindValue"); Assert.AreEqual(StoreLocation.CurrentUser, element.ClientCertificate.Certificate.StoreLocation, "ClientCertificate.Certificate.StoreLocation"); Assert.AreEqual(StoreName.Root, element.ClientCertificate.Certificate.StoreName, "ClientCertificate.Certificate.StoreName"); Assert.AreEqual(X509FindType.FindByIssuerName, element.ClientCertificate.Certificate.X509FindType, "ClientCertificate.Certificate.X509FindType"); Assert.AreEqual("CustomCertificateValidationType", element.ClientCertificate.Authentication.CustomCertificateValidatorType, "ClientCertificate.Authentication.CustomCertificateValidatorType"); Assert.AreEqual(X509CertificateValidationMode.PeerOrChainTrust, element.ClientCertificate.Authentication.CertificateValidationMode, "ClientCertificate.Authentication.CustomCertificateValidatorType"); Assert.AreEqual(X509RevocationMode.Offline, element.ClientCertificate.Authentication.RevocationMode, "ClientCertificate.Authentication.RevocationMode"); Assert.AreEqual(StoreLocation.CurrentUser, element.ClientCertificate.Authentication.TrustedStoreLocation, "ClientCertificate.Authentication.TrustedStoreLocation"); Assert.AreEqual(false, element.ClientCertificate.Authentication.IncludeWindowsGroups, "ClientCertificate.Authentication.IncludeWindowsGroups"); Assert.AreEqual(true, element.ClientCertificate.Authentication.MapClientCertificateToWindowsAccount, "ClientCertificate.Authentication.MapClientCertificateToWindowsAccount"); Assert.AreEqual("FindValue", element.ServiceCertificate.FindValue, "ServiceCertificate.FindValue"); Assert.AreEqual(StoreLocation.CurrentUser, element.ServiceCertificate.StoreLocation, "ServiceCertificate.StoreLocation"); Assert.AreEqual(StoreName.Root, element.ServiceCertificate.StoreName, "ServiceCertificate.StoreName"); Assert.AreEqual(X509FindType.FindByIssuerName, element.ServiceCertificate.X509FindType, "ServiceCertificate.X509FindType"); Assert.AreEqual(UserNamePasswordValidationMode.MembershipProvider, element.UserNameAuthentication.UserNamePasswordValidationMode, "UserNameAuthentication.UserNamePasswordValidationMode"); Assert.AreEqual(false, element.UserNameAuthentication.IncludeWindowsGroups, "UserNameAuthentication.IncludeWindowsGroups"); Assert.AreEqual("MembershipProviderName", element.UserNameAuthentication.MembershipProviderName, "UserNameAuthentication.MembershipProviderName"); Assert.AreEqual("CustomUserNamePasswordValidatorType", element.UserNameAuthentication.CustomUserNamePasswordValidatorType, "UserNameAuthentication.customUserNamePasswordValidatorType"); Assert.AreEqual(true, element.UserNameAuthentication.CacheLogonTokens, "UserNameAuthentication.CacheLogonTokens"); Assert.AreEqual(252, element.UserNameAuthentication.MaxCachedLogonTokens, "UserNameAuthentication.MaxCachedLogonTokens"); Assert.AreEqual(new TimeSpan(0, 30, 0), element.UserNameAuthentication.CachedLogonTokenLifetime, "UserNameAuthentication.CachedLogonTokenLifetime"); Assert.AreEqual("FindValue", element.Peer.Certificate.FindValue, "Peer.Certificate.FindValue"); Assert.AreEqual(StoreLocation.LocalMachine, element.Peer.Certificate.StoreLocation, "Peer.Certificate.StoreLocation"); Assert.AreEqual(StoreName.Root, element.Peer.Certificate.StoreName, "Peer.Certificate.StoreName"); Assert.AreEqual(X509FindType.FindByIssuerName, element.Peer.Certificate.X509FindType, "Peer.Certificate.X509FindType"); Assert.AreEqual("CustomCertificateValidatorType", element.Peer.PeerAuthentication.CustomCertificateValidatorType, "Peer.Authentication.CustomCertificateValidatorType"); Assert.AreEqual(X509CertificateValidationMode.Custom, element.Peer.PeerAuthentication.CertificateValidationMode, "Peer.Authentication.CustomCertificateValidatorType"); Assert.AreEqual(X509RevocationMode.Offline, element.Peer.PeerAuthentication.RevocationMode, "Peer.Authentication.RevocationMode"); Assert.AreEqual(StoreLocation.LocalMachine, element.Peer.PeerAuthentication.TrustedStoreLocation, "Peer.Authentication.TrustedStoreLocation"); Assert.AreEqual("CustomCertificateValidatorType", element.Peer.MessageSenderAuthentication.CustomCertificateValidatorType, "Peer.MessageSenderAuthentication.CustomCertificateValidatorType"); Assert.AreEqual(X509CertificateValidationMode.None, element.Peer.MessageSenderAuthentication.CertificateValidationMode, "Peer.MessageSenderAuthentication.CustomCertificateValidatorType"); Assert.AreEqual(X509RevocationMode.Offline, element.Peer.MessageSenderAuthentication.RevocationMode, "Peer.MessageSenderAuthentication.RevocationMode"); Assert.AreEqual(StoreLocation.LocalMachine, element.Peer.MessageSenderAuthentication.TrustedStoreLocation, "Peer.MessageSenderAuthentication.TrustedStoreLocation"); Assert.AreEqual("CustomCertificateValidatorType", element.IssuedTokenAuthentication.CustomCertificateValidatorType, "IssuedTokenAuthentication.CustomCertificateValidatorType"); Assert.AreEqual(X509CertificateValidationMode.PeerOrChainTrust, element.IssuedTokenAuthentication.CertificateValidationMode, "IssuedTokenAuthentication.CustomCertificateValidatorType"); Assert.AreEqual(X509RevocationMode.Offline, element.IssuedTokenAuthentication.RevocationMode, "IssuedTokenAuthentication.RevocationMode"); Assert.AreEqual(StoreLocation.CurrentUser, element.IssuedTokenAuthentication.TrustedStoreLocation, "IssuedTokenAuthentication.TrustedStoreLocation"); Assert.AreEqual("SalmSerializerType", element.IssuedTokenAuthentication.SamlSerializerType, "IssuedTokenAuthentication.SamlSerializerType"); Assert.AreEqual(true, element.IssuedTokenAuthentication.AllowUntrustedRsaIssuers, "IssuedTokenAuthentication.AllowUntrustedRsaIssuers"); Assert.AreEqual("FindValue", element.IssuedTokenAuthentication.KnownCertificates [0].FindValue, "IssuedTokenAuthentication.KnownCertificates[0].FindValue"); Assert.AreEqual(StoreLocation.CurrentUser, element.IssuedTokenAuthentication.KnownCertificates [0].StoreLocation, "IssuedTokenAuthentication.KnownCertificates[0].StoreLocation"); Assert.AreEqual(StoreName.Root, element.IssuedTokenAuthentication.KnownCertificates [0].StoreName, "IssuedTokenAuthentication.KnownCertificates[0].StoreName"); Assert.AreEqual(X509FindType.FindByIssuerName, element.IssuedTokenAuthentication.KnownCertificates [0].X509FindType, "IssuedTokenAuthentication.KnownCertificates[0].X509FindType"); Assert.AreEqual("SecurityStateEncoderType", element.SecureConversationAuthentication.SecurityStateEncoderType, "SecureConversationAuthentication.SecurityStateEncoderType"); }