protected override object GetElementKey(ConfigurationElement element)
        {
            // Get index name
            ExtensionElement extension = (ExtensionElement)element;

            return(extension.Name);
        }
        /// <summary>
        /// Returns the property descriptors for this instance.
        /// </summary>
        public override PropertyDescriptorCollection GetProperties(ITypeDescriptorContext context, object value, Attribute[] attributes)
        {
            Guard.NotNull(() => context, context);

            var descriptors = base.GetProperties(context, value, attributes).Cast <PropertyDescriptor>();

            // Remove descriptors for the data type of this property (string)
            descriptors = descriptors.Where(descriptor => descriptor.ComponentType != typeof(string));

            // Get the model element being described
            var          selection = context.Instance;
            ModelElement mel       = selection as ModelElement;
            var          pel       = selection as PresentationElement;

            if (pel != null)
            {
                mel = pel.Subject;
            }

            var element = ExtensionElement.GetExtension <ArtifactExtension>(mel);

            if (element != null)
            {
                // Copy descriptors from owner (make Browsable)
                var descriptor1 = new DelegatingPropertyDescriptor(element, TypedDescriptor.CreateProperty(element, extension => extension.OnArtifactActivation),
                                                                   new BrowsableAttribute(true), new DefaultValueAttribute(element.GetPropertyDefaultValue <ArtifactExtension, ArtifactActivatedAction>(e => e.OnArtifactActivation)));
                var descriptor2 = new DelegatingPropertyDescriptor(element, TypedDescriptor.CreateProperty(element, extension => extension.OnArtifactDeletion),
                                                                   new BrowsableAttribute(true), new DefaultValueAttribute(element.GetPropertyDefaultValue <ArtifactExtension, ArtifactDeletedAction>(e => e.OnArtifactDeletion)));
                descriptors = descriptors.Concat(new[] { descriptor1, descriptor2 });
            }

            return(new PropertyDescriptorCollection(descriptors.ToArray()));
        }
예제 #3
0
        public static void ParseChildElements(string elementName, BaseElement parentElement, XMLStreamReader xtr, IDictionary <string, BaseChildElementParser> childParsers, BpmnModel model)
        {
            IDictionary <string, BaseChildElementParser> localParserMap = new Dictionary <string, BaseChildElementParser>(genericChildParserMap);

            if (childParsers != null)
            {
                localParserMap.PutAll(childParsers);
            }

            bool inExtensionElements    = false;
            bool readyWithChildElements = false;

            while (!readyWithChildElements && xtr.HasNext())
            {
                //xtr.next();

                if (xtr.IsStartElement())
                {
                    if (BpmnXMLConstants.ELEMENT_EXTENSIONS.Equals(xtr.LocalName))
                    {
                        inExtensionElements = true;
                    }
                    else if (localParserMap.ContainsKey(xtr.LocalName))
                    {
                        BaseChildElementParser childParser = localParserMap[xtr.LocalName];
                        //if we're into an extension element but the current element is not accepted by this parentElement then is read as a custom extension element
                        if (inExtensionElements && !childParser.Accepts(parentElement))
                        {
                            ExtensionElement extensionElement = BpmnXMLUtil.ParseExtensionElement(xtr);
                            parentElement.AddExtensionElement(extensionElement);
                            continue;
                        }
                        localParserMap[xtr.LocalName].ParseChildElement(xtr, parentElement, model);
                    }
                    else if (inExtensionElements)
                    {
                        ExtensionElement extensionElement = BpmnXMLUtil.ParseExtensionElement(xtr);
                        parentElement.AddExtensionElement(extensionElement);
                    }
                }
                else if (xtr.EndElement)
                {
                    if (BpmnXMLConstants.ELEMENT_EXTENSIONS.Equals(xtr.LocalName))
                    {
                        inExtensionElements = false;
                    }
                    else if (elementName.Equals(xtr.LocalName, StringComparison.CurrentCultureIgnoreCase))
                    {
                        readyWithChildElements = true;
                    }
                }

                if (xtr.IsEmptyElement && elementName.Equals(xtr.LocalName, StringComparison.OrdinalIgnoreCase))
                {
                    readyWithChildElements = true;
                }
            }
        }
예제 #4
0
        public static IReportRunner GetReportRunner(string runnerType)
        {
            Guard.ArgumentNotNullOrEmptyString(runnerType, "runnerType");
            ExtensionElement extnElement = ExtensionsSection.ThisSection.GetExtensions(ReportsSection.REPORT_RUNNERS)[runnerType];

            if (extnElement == null)
            {
                throw new ArgumentOutOfRangeException(string.Format("Runner type {0} not configured", runnerType));
            }
            return(Reflection.CreateInstance <IReportRunner>(extnElement.Type));
        }
            public void InitializeContext()
            {
                this.store.TransactionManager.DoWithinTransaction(() =>
                {
                    var patternModel  = store.ElementFactory.CreateElement <PatternModelSchema>();
                    this.product      = patternModel.Create <PatternSchema>();
                    this.product.Name = "WebService";
                });

                this.validationExtension = ExtensionElement.GetExtension <ValidationExtension>(this.product);
            }
예제 #6
0
            public void ShouldBeAbleToAddAnExtensionToADerivedClass()
            {
                KmlFactory.Register <BaseElement>(new XmlComponent(null, nameof(BaseElement), nameof(ElementTest)));
                KmlFactory.Register <DerivedElement>(new XmlComponent(null, nameof(DerivedElement), nameof(ElementTest)));
                KmlFactory.RegisterExtension <BaseElement, ExtensionElement>();

                var parent = new DerivedElement();
                var child  = new ExtensionElement();

                parent.AddChild(child);

                Assert.That(parent.Children, Has.Member(child));
            }
        public virtual void Parse(XMLStreamReader xtr, IList <SubProcess> activeSubProcessList, Process activeProcess, BpmnModel model)
        {
            BaseElement parentElement;

            if (activeSubProcessList.Count > 0)
            {
                parentElement = activeSubProcessList[activeSubProcessList.Count - 1];
            }
            else
            {
                parentElement = activeProcess;
            }

            bool readyWithChildElements = false;

            while (readyWithChildElements == false && xtr.HasNext())
            {
                //xtr.next();

                if (xtr.IsStartElement())
                {
                    if (BpmnXMLConstants.ELEMENT_EXECUTION_LISTENER.Equals(xtr.LocalName))
                    {
                        (new ExecutionListenerParser()).ParseChildElement(xtr, parentElement, model);
                    }
                    else if (BpmnXMLConstants.ELEMENT_EVENT_LISTENER.Equals(xtr.LocalName))
                    {
                        (new ActivitiEventListenerParser()).ParseChildElement(xtr, parentElement, model);
                    }
                    else if (BpmnXMLConstants.ELEMENT_POTENTIAL_STARTER.Equals(xtr.LocalName))
                    {
                        (new PotentialStarterParser()).Parse(xtr, activeProcess);
                    }
                    else
                    {
                        ExtensionElement extensionElement = BpmnXMLUtil.ParseExtensionElement(xtr);
                        parentElement.AddExtensionElement(extensionElement);
                    }
                }
                else if (xtr.EndElement && BpmnXMLConstants.ELEMENT_EXTENSIONS.Equals(xtr.LocalName))
                {
                    readyWithChildElements = true;
                }

                if (xtr.IsEmptyElement && string.Compare(xtr.LocalName, BpmnXMLConstants.ELEMENT_EXTENSIONS, true) == 0)
                {
                    readyWithChildElements = true;
                }
            }
        }
예제 #8
0
        public void AddMachineConfigurationInfo()
        {
            System.Configuration.Configuration config = ConfigurationManager.OpenMachineConfiguration();
            Debug.Assert(config != null, "Machine.Config returned null");
            ServiceModelSectionGroup sectionGroup = config.GetSectionGroup("system.serviceModel") as ServiceModelSectionGroup;

            if (sectionGroup != null)
            {
                bool          channelEndpointElementExists = false;
                ClientSection clientSection = sectionGroup.Client;
                foreach (ChannelEndpointElement elem in clientSection.Endpoints)
                {
                    if (elem.Binding.Equals(BINDING_NAME, StringComparison.OrdinalIgnoreCase) && elem.Name.Equals(BINDING_SCHEME, StringComparison.OrdinalIgnoreCase) && elem.Contract.Equals("IMetadataExchange", StringComparison.OrdinalIgnoreCase))
                    {
                        channelEndpointElementExists = true;
                        break;
                    }
                }
                if (!channelEndpointElementExists)
                {
                    Debug.WriteLine("Adding ChannelEndpointElement for : " + BINDING_NAME);
                    ChannelEndpointElement elem = new ChannelEndpointElement();
                    elem.Binding  = BINDING_NAME;
                    elem.Name     = BINDING_SCHEME;
                    elem.Contract = "IMetadataExchange";
                    sectionGroup.Client.Endpoints.Add(elem);
                    Debug.WriteLine("Added ChannelEndpointElement for : " + BINDING_NAME);
                }

                if (!sectionGroup.Extensions.BindingElementExtensions.ContainsKey(BINDINGELEM_NAME))
                {
                    ExtensionElement ext = new ExtensionElement(BINDINGELEM_NAME, bindingElementExtensionType.FullName + "," + bindingElementExtensionType.Assembly.FullName);
                    sectionGroup.Extensions.BindingElementExtensions.Add(ext);
                }

                if (!sectionGroup.Extensions.BindingExtensions.ContainsKey(BINDING_NAME))
                {
                    ExtensionElement ext = new ExtensionElement(BINDING_NAME, bindingSectionType.FullName + "," + bindingSectionType.Assembly.FullName);
                    sectionGroup.Extensions.BindingExtensions.Add(ext);
                }

                config.Save();
            }
            else
            {
                throw new InstallException("Machine.Config doesn't contain system.serviceModel node");
            }
        }
예제 #9
0
        protected internal virtual ExtensionElement ParseExtensionElement(XMLStreamReader xtr)
        {
            ExtensionElement extensionElement = new ExtensionElement
            {
                Name = xtr.LocalName
            };

            if (!string.IsNullOrWhiteSpace(xtr.NamespaceURI))
            {
                extensionElement.Namespace = xtr.NamespaceURI;
            }
            if (!string.IsNullOrWhiteSpace(xtr.Prefix))
            {
                extensionElement.NamespacePrefix = xtr.Prefix;
            }

            BpmnXMLUtil.AddCustomAttributes(xtr, extensionElement, defaultElementAttributes);

            bool readyWithExtensionElement = false;

            while (!readyWithExtensionElement && xtr.HasNext())
            {
                //xtr.next();

                if (xtr.NodeType == XmlNodeType.CDATA)
                {
                    if (!string.IsNullOrWhiteSpace(xtr.Value?.Trim()))
                    {
                        extensionElement.ElementText = xtr.Value?.Trim();
                    }
                }
                else if (xtr.IsStartElement())
                {
                    ExtensionElement childExtensionElement = ParseExtensionElement(xtr);
                    extensionElement.AddChildElement(childExtensionElement);
                }
                else if (xtr.EndElement && string.Compare(extensionElement.Name, xtr.LocalName, true) == 0)
                {
                    readyWithExtensionElement = true;
                }

                if (xtr.IsEmptyElement && string.Compare(extensionElement.Name, xtr.LocalName, true) == 0)
                {
                    readyWithExtensionElement = true;
                }
            }
            return(extensionElement);
        }
예제 #10
0
        public static ExtensionElement ParseExtensionElement(XMLStreamReader xtr)
        {
            ExtensionElement extensionElement = CreateExtensionElement(xtr);

            bool readyWithExtensionElement = false;

            while (!readyWithExtensionElement && xtr.HasNext())
            {
                //xtr.next();

                if (xtr.NodeType == XmlNodeType.Text || xtr.NodeType == XmlNodeType.CDATA)
                {
                    if (!string.IsNullOrWhiteSpace(xtr.Value?.Trim()))
                    {
                        extensionElement.ElementText = xtr.Value?.Trim();
                    }
                }
                else if (xtr.IsStartElement())
                {
                    if (xtr.IsEmptyElement)
                    {
                        ExtensionElement childExtensionElement = CreateExtensionElement(xtr);
                        extensionElement.AddChildElement(childExtensionElement);
                        xtr.isEmpty = xtr.IsStartElement() && xtr.EndElement;
                        xtr.Next();
                        return(childExtensionElement);
                    }
                    else
                    {
                        ExtensionElement childExtensionElement = ParseExtensionElement(xtr);
                        extensionElement.AddChildElement(childExtensionElement);
                    }
                }
                else if (xtr.EndElement && string.Compare(extensionElement.Name, xtr.LocalName, true) == 0)
                {
                    readyWithExtensionElement = true;
                }

                if (xtr.IsEmptyElement && string.Compare(extensionElement.Name, xtr.LocalName, true) == 0)
                {
                    readyWithExtensionElement = true;
                }
            }
            return(extensionElement);
        }
예제 #11
0
        /// <inheritdoc />
        private IList <ProcessDefinitionVariable> GetVariables(Process process)
        {
            IList <ProcessDefinitionVariable> variables = new List <ProcessDefinitionVariable>();

            if (process.ExtensionElements.Count > 0)
            {
                IEnumerator <IList <ExtensionElement> > it = process.ExtensionElements.Values.GetEnumerator();
                while (it.MoveNext())
                {
                    IList <ExtensionElement>       extensionElementList = it.Current;
                    IEnumerator <ExtensionElement> it2 = extensionElementList.GetEnumerator();
                    while (it2.MoveNext())
                    {
                        ExtensionElement          ee       = it2.Current;
                        string                    name     = ee.GetAttributeValue(ee.Namespace, "variableName");
                        string                    type     = ee.GetAttributeValue(ee.Namespace, "variableType");
                        ProcessDefinitionVariable variable = new ProcessDefinitionVariable(name, type);
                        variables.Add(variable);
                    }
                }
            }
            return(variables);
        }
예제 #12
0
        /// <summary>
        /// Starts the windows service
        /// </summary>
        void IService.OnStart()
        {
            ExtensionElement extnElement = ExtensionsSection.ThisSection.Settings["ITaskManagerConfig"];

            string configTypeString = null;

            if (extnElement != null)
            {
                configTypeString = extnElement.Type;
            }

            ITaskManagerConfig tmConfig;

            if (!string.IsNullOrEmpty(configTypeString))
            {
                tmConfig = Reflection.CreateInstance <ITaskManagerConfig>(configTypeString);
            }
            else
            {
                tmConfig = new TaskManagerConfig();
            }
            TaskManager.Start(tmConfig);
        }
예제 #13
0
        private static ExtensionElement CreateExtensionElement(XMLStreamReader xtr)
        {
            ExtensionElement extensionElement = new ExtensionElement
            {
                Name = xtr.LocalName
            };

            if (!string.IsNullOrWhiteSpace(xtr.NamespaceURI))
            {
                extensionElement.Namespace = xtr.NamespaceURI;
            }
            if (!string.IsNullOrWhiteSpace(xtr.Prefix))
            {
                extensionElement.NamespacePrefix = xtr.Prefix;
            }

            foreach (var attr in xtr.element.Attributes())
            {
                ExtensionAttribute extensionAttribute = new ExtensionAttribute
                {
                    Name  = attr.Name.LocalName,
                    Value = attr.Value
                };
                if (!string.IsNullOrWhiteSpace(attr.Name.NamespaceName))
                {
                    extensionAttribute.Namespace = attr.Name.NamespaceName;
                }
                if (!string.IsNullOrWhiteSpace(xtr.element.GetPrefixOfNamespace(attr.Name.NamespaceName)))
                {
                    extensionAttribute.NamespacePrefix = xtr.element.GetPrefixOfNamespace(attr.Name.NamespaceName);
                }
                extensionElement.AddAttribute(extensionAttribute);
            }

            return(extensionElement);
        }
        protected internal override BaseElement ConvertXMLToElement(XMLStreamReader xtr, BpmnModel model)
        {
            ValuedDataObject dataObject     = null;
            ItemDefinition   itemSubjectRef = new ItemDefinition();

            string structureRef = xtr.GetAttributeValue(BpmnXMLConstants.ATTRIBUTE_DATA_ITEM_REF);

            if (!string.IsNullOrWhiteSpace(structureRef) && structureRef.Contains(":"))
            {
                string dataType = structureRef.Substring(structureRef.IndexOf(':') + 1);

                if (dataType.Equals("string"))
                {
                    dataObject = new StringDataObject();
                }
                else if (dataType.Equals("int"))
                {
                    dataObject = new IntegerDataObject();
                }
                else if (dataType.Equals("long"))
                {
                    dataObject = new LongDataObject();
                }
                else if (dataType.Equals("double"))
                {
                    dataObject = new DoubleDataObject();
                }
                else if (dataType.Equals("boolean"))
                {
                    dataObject = new BooleanDataObject();
                }
                else if (dataType.Equals("datetime"))
                {
                    dataObject = new DateDataObject();
                }
                else
                {
                    logger.LogError($"Error converting {xtr.GetAttributeValue(BpmnXMLConstants.ATTRIBUTE_DATA_NAME)}, invalid data type: {dataType}");
                }
            }
            else
            {
                // use String as default type
                dataObject   = new StringDataObject();
                structureRef = "xsd:string";
            }

            if (dataObject != null)
            {
                dataObject.Id   = xtr.GetAttributeValue(BpmnXMLConstants.ATTRIBUTE_DATA_ID);
                dataObject.Name = xtr.GetAttributeValue(BpmnXMLConstants.ATTRIBUTE_DATA_NAME);

                BpmnXMLUtil.AddXMLLocation(dataObject, xtr);

                itemSubjectRef.StructureRef = structureRef;
                dataObject.ItemSubjectRef   = itemSubjectRef;

                ParseChildElements(XMLElementName, dataObject, model, xtr);

                dataObject.ExtensionElements.TryGetValue("value", out IList <ExtensionElement> valuesElement);
                if (valuesElement != null && valuesElement.Count > 0)
                {
                    ExtensionElement valueElement = valuesElement[0];
                    if (!string.IsNullOrWhiteSpace(valueElement.ElementText))
                    {
                        if (dataObject is DateDataObject)
                        {
                            try
                            {
                                dataObject.Value = DateTime.Parse(valueElement.ElementText, new DateTimeFormatInfo()
                                {
                                    FullDateTimePattern = sdf
                                });
                            }
                            catch (Exception e)
                            {
                                logger.LogError(e, $"Error converting {dataObject.Name} \r\n {e.Message}");
                            }
                        }
                        else
                        {
                            dataObject.Value = valueElement.ElementText;
                        }
                    }

                    // remove value element
                    dataObject.ExtensionElements.Remove("value");
                }
            }

            return(dataObject);
        }
 static ExtensionElement()
 {
     DefaultValue = new ExtensionElement("jsx");
 }
예제 #16
0
        private void Run()
        {
            //<snippet1>
            Configuration machine = ConfigurationManager.OpenMachineConfiguration();
            //<snippet5>
            // Register our validator configuration element.
            ExtensionsSection extensions
                = machine.GetSection(@"system.serviceModel/extensions") as ExtensionsSection;

            if (extensions == null)
            {
                throw new Exception("not extensions section.");
            }
            ExtensionElement validator
                = new ExtensionElement(
                      "internetClientValidator",
                      "Microsoft.ServiceModel.Samples.InternetClientValidatorElement, InternetClientValidator, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"
                      );

            validator.LockItem = true;
            if (extensions.BehaviorExtensions.IndexOf(validator) < 0)
            {
                extensions.BehaviorExtensions.Add(validator);
            }
            //</snippet5>

            //<snippet6>
            // Add a new section for our validator and lock it down.
            // Behaviors for client applications must be endpoint behaviors.
            // Behaviors for service applications must be service behaviors.
            CommonBehaviorsSection commonBehaviors
                = machine.GetSection(@"system.serviceModel/commonBehaviors") as CommonBehaviorsSection;
            InternetClientValidatorElement internetValidator = new InternetClientValidatorElement();

            internetValidator.LockItem = true;
            commonBehaviors.EndpointBehaviors.Add(internetValidator);
            //</snippet6>
            //<snippet7>
            // Write to disk.
            machine.SaveAs("newMachine.config");

            // Write our new information.
            SectionInformation cBInfo = commonBehaviors.SectionInformation;

            Console.WriteLine(cBInfo.GetRawXml());
            Console.WriteLine(extensions.SectionInformation.GetRawXml());
            Console.Read();
            //</snippet7>
            //</snippet1>

            /*
             * //<snippet4>
             * <extensions>
             * <behaviorExtensions>
             * <add
             *  name="internetClientValidator"
             *  type="Microsoft.ServiceModel.Samples.InternetClientValidatorElement, InternetClientValidator, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"
             *  lockItem="true" />
             * </behaviorExtensions>
             * </extensions>
             * <commonBehaviors>
             * <endpointBehaviors>
             * <internetClientValidator lockItem="true" />
             * </endpointBehaviors>
             * </commonBehaviors>
             * //</snippet4>
             *
             */
        }
 public void Add(ExtensionElement item)
 {
     base.BaseAdd(item);
 }
 public void Remove(ExtensionElement item)
 {
     base.BaseRemove(item);
 }
예제 #19
0
        protected internal static void WriteExtensionElement(ExtensionElement extensionElement, IDictionary <string, string> namespaceMap, XMLStreamWriter xtw)
        {
            if (!string.IsNullOrWhiteSpace(extensionElement.Name))
            {
                IDictionary <string, string> localNamespaceMap = new Dictionary <string, string>();
                if (!string.IsNullOrWhiteSpace(extensionElement.Namespace))
                {
                    if (!string.IsNullOrWhiteSpace(extensionElement.NamespacePrefix))
                    {
                        xtw.WriteStartElement(extensionElement.NamespacePrefix, extensionElement.Name, extensionElement.Namespace);

                        if (!namespaceMap.ContainsKey(extensionElement.NamespacePrefix) || !namespaceMap[extensionElement.NamespacePrefix].Equals(extensionElement.Namespace))
                        {
                            xtw.WriteNamespace(extensionElement.NamespacePrefix, extensionElement.Namespace);
                            namespaceMap[extensionElement.NamespacePrefix]      = extensionElement.Namespace;
                            localNamespaceMap[extensionElement.NamespacePrefix] = extensionElement.Namespace;
                        }
                    }
                    else
                    {
                        xtw.WriteStartElement(extensionElement.Namespace, extensionElement.Name);
                    }
                }
                else
                {
                    xtw.WriteStartElement(BpmnXMLConstants.BPMN_PREFIX, extensionElement.Name, BpmnXMLConstants.BPMN2_NAMESPACE);
                }

                foreach (IList <ExtensionAttribute> attributes in extensionElement.Attributes.Values)
                {
                    foreach (ExtensionAttribute attribute in attributes)
                    {
                        if (!string.IsNullOrWhiteSpace(attribute.Name) && attribute.Value != null)
                        {
                            if (!string.IsNullOrWhiteSpace(attribute.Namespace))
                            {
                                if (!string.IsNullOrWhiteSpace(attribute.NamespacePrefix))
                                {
                                    if (!namespaceMap.ContainsKey(attribute.NamespacePrefix) || !namespaceMap[attribute.NamespacePrefix].Equals(attribute.Namespace))
                                    {
                                        xtw.WriteNamespace(attribute.NamespacePrefix, attribute.Namespace);
                                        namespaceMap[attribute.NamespacePrefix] = attribute.Namespace;
                                    }

                                    xtw.WriteAttribute(attribute.NamespacePrefix, attribute.Namespace, attribute.Name, attribute.Value);
                                }
                                else
                                {
                                    xtw.WriteAttribute(attribute.Namespace, attribute.Name, attribute.Value);
                                }
                            }
                            else
                            {
                                xtw.WriteAttribute(attribute.Name, attribute.Value);
                            }
                        }
                    }
                }

                if (extensionElement.ElementText != null)
                {
                    xtw.WriteCData(extensionElement.ElementText);
                }
                else
                {
                    foreach (IList <ExtensionElement> childElements in extensionElement.ChildElements.Values)
                    {
                        foreach (ExtensionElement childElement in childElements)
                        {
                            WriteExtensionElement(childElement, namespaceMap, xtw);
                        }
                    }
                }

                foreach (string prefix in localNamespaceMap.Keys)
                {
                    namespaceMap.Remove(prefix);
                }

                xtw.WriteEndElement();
            }
        }
예제 #20
0
        /// <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";
                    }
                }
            }
        }
예제 #21
0
        /// <summary>
        /// Registers the adapter with the WCF configuration
        /// </summary>
        public static void AddMachineConfigurationInfo(string installDir,
                                                       System.Configuration.Configuration config)
        {
            Assembly adapterAssembly;
            Type     bindingSectionType;
            Type     bindingElementExtensionType;

            string path = System.IO.Path.Combine(installDir, BINDING_ASSEMBLY_NAME);

            adapterAssembly = Assembly.LoadFrom(path);

            Debug.Assert(adapterAssembly != null, "Adapter assembly is null.");

            bindingSectionType = adapterAssembly.GetType(BINDING_TYPE, true);
            Debug.Assert(bindingSectionType != null, "Binding type is null.");

            bindingElementExtensionType = adapterAssembly.GetType(BINDINGELEM_TYPE, true);
            Debug.Assert(bindingElementExtensionType != null, "Binding element extension type is null.");

            // add <client><endpoint>
            ServiceModelSectionGroup sectionGroup = config.GetSectionGroup("system.serviceModel") as ServiceModelSectionGroup;

            if (sectionGroup != null)
            {
                bool channelEndpointElementExists = false;
                // this call can throw an exception if there is problem
                // loading endpoint configurations - e.g. each endpoint
                // tries to load binding which in turn loads the DLL
                ClientSection clientSection = sectionGroup.Client;
                foreach (ChannelEndpointElement elem in clientSection.Endpoints)
                {
                    if (elem.Binding.Equals(BINDING_NAME, StringComparison.OrdinalIgnoreCase) &&
                        elem.Name.Equals(BINDING_SCHEME, StringComparison.OrdinalIgnoreCase) &&
                        elem.Contract.Equals("IMetadataExchange", StringComparison.OrdinalIgnoreCase))
                    {
                        channelEndpointElementExists = true;
                        break;
                    }
                }
                if (!channelEndpointElementExists)
                {
                    Debug.WriteLine("Adding ChannelEndpointElement for : " + BINDING_NAME);

                    ChannelEndpointElement elem = new ChannelEndpointElement();
                    elem.Binding  = BINDING_NAME;
                    elem.Name     = BINDING_SCHEME;
                    elem.Contract = "IMetadataExchange";
                    sectionGroup.Client.Endpoints.Add(elem);

                    Debug.WriteLine("Added ChannelEndpointElement for : " + BINDING_NAME);
                }

                // add <bindingElementExtension>
                if (!sectionGroup.Extensions.BindingElementExtensions.ContainsKey(BINDINGELEM_NAME))
                {
                    ExtensionElement ext = new ExtensionElement(BINDINGELEM_NAME,
                                                                bindingElementExtensionType.FullName + ", " + bindingElementExtensionType.Assembly.FullName);
                    sectionGroup.Extensions.BindingElementExtensions.Add(ext);
                }

                // add <bindingExtension>
                if (!sectionGroup.Extensions.BindingExtensions.ContainsKey(BINDING_NAME))
                {
                    ExtensionElement ext = new ExtensionElement(BINDING_NAME,
                                                                bindingSectionType.FullName + ", " + bindingSectionType.Assembly.FullName);
                    sectionGroup.Extensions.BindingExtensions.Add(ext);
                }

                config.Save();
            }
            else
            {
                throw new ApplicationException("Machine.Config doesn't contain system.serviceModel node");
            }
        }