Example #1
0
 private void WriteFacets(XmlSchemaObjectCollection facets)
 {
     if (facets != null)
     {
         ArrayList list = new ArrayList();
         for (int i = 0; i < facets.Count; i++)
         {
             list.Add(facets[i]);
         }
         list.Sort(new XmlFacetComparer());
         for (int j = 0; j < list.Count; j++)
         {
             XmlSchemaObject obj2 = (XmlSchemaObject)list[j];
             if (obj2 is XmlSchemaMinExclusiveFacet)
             {
                 this.Write_XmlSchemaFacet("minExclusive", (XmlSchemaFacet)obj2);
             }
             else if (obj2 is XmlSchemaMaxInclusiveFacet)
             {
                 this.Write_XmlSchemaFacet("maxInclusive", (XmlSchemaFacet)obj2);
             }
             else if (obj2 is XmlSchemaMaxExclusiveFacet)
             {
                 this.Write_XmlSchemaFacet("maxExclusive", (XmlSchemaFacet)obj2);
             }
             else if (obj2 is XmlSchemaMinInclusiveFacet)
             {
                 this.Write_XmlSchemaFacet("minInclusive", (XmlSchemaFacet)obj2);
             }
             else if (obj2 is XmlSchemaLengthFacet)
             {
                 this.Write_XmlSchemaFacet("length", (XmlSchemaFacet)obj2);
             }
             else if (obj2 is XmlSchemaEnumerationFacet)
             {
                 this.Write_XmlSchemaFacet("enumeration", (XmlSchemaFacet)obj2);
             }
             else if (obj2 is XmlSchemaMinLengthFacet)
             {
                 this.Write_XmlSchemaFacet("minLength", (XmlSchemaFacet)obj2);
             }
             else if (obj2 is XmlSchemaPatternFacet)
             {
                 this.Write_XmlSchemaFacet("pattern", (XmlSchemaFacet)obj2);
             }
             else if (obj2 is XmlSchemaTotalDigitsFacet)
             {
                 this.Write_XmlSchemaFacet("totalDigits", (XmlSchemaFacet)obj2);
             }
             else if (obj2 is XmlSchemaMaxLengthFacet)
             {
                 this.Write_XmlSchemaFacet("maxLength", (XmlSchemaFacet)obj2);
             }
             else if (obj2 is XmlSchemaWhiteSpaceFacet)
             {
                 this.Write_XmlSchemaFacet("whiteSpace", (XmlSchemaFacet)obj2);
             }
             else if (obj2 is XmlSchemaFractionDigitsFacet)
             {
                 this.Write_XmlSchemaFacet("fractionDigit", (XmlSchemaFacet)obj2);
             }
         }
     }
 }
Example #2
0
        private void button1_Click(object sender, EventArgs e)
        {
            Logger.Text = "";
            XmlTextReader xmlr = null;

            System.Web.Services.Description.ServiceDescription  servdesc = null;
            System.Web.Services.Description.PortTypeCollection  ports    = null;
            System.Web.Services.Description.OperationCollection ops      = null;
            System.Xml.Serialization.XmlSchemas schemas = null;

            for (int i = 0; i < httpheaderlist.Items.Count; i++)
            {
                httpheaderlist.Items.RemoveAt(i);
            }
            if (!urltext.Text.StartsWith("http"))
            {
                MessageBox.Show("Please enter a URL starting with http");
                return;
            }
            if (urltext.Text.IndexOf("://") == -1)
            {
                MessageBox.Show("Did you forget the protocol like http:// or https:// ?" +
                                "\r\n E.g., http://soap.amazon.com/schemas2/AmazonWebServices.wsdl");
                return;
            }
            try
            {
                xmlr = new XmlTextReader(urltext.Text);
                xmlr.WhitespaceHandling = WhitespaceHandling.None;
                servdesc     = System.Web.Services.Description.ServiceDescription.Read(xmlr);
                schemas      = servdesc.Types.Schemas;
                Logger.Text += "=== Found " + schemas.Count + " schema(s)===\r\n";

                for (int k = 0; k < schemas.Count; k++)
                {
                    XmlSchemaObjectCollection xmlelem    = schemas[k].Items;
                    XmlSchemaObjectEnumerator enumerator = xmlelem.GetEnumerator();
                    while (enumerator.MoveNext())
                    {
                        if (enumerator.Current is XmlSchemaElement)
                        {
                            XmlSchemaElement xse = (XmlSchemaElement)enumerator.Current;
                            Logger.Text += xse.Name + '=' + xse.SchemaType + ", ";
                            TraverseParticle(xse);
                        }
                        else
                        {
                            if (enumerator.Current is XmlSchemaComplexType)
                            {
                                XmlSchemaComplexType xsct = (XmlSchemaComplexType)enumerator.Current;
                                Logger.Text += '\'' + xsct.Name + ": ";
                                TraverseParticle(xsct.Particle);
                                if (xsct.ContentModel is XmlSchemaSimpleContent)
                                {
                                    Logger.Text += "Simple; ";
                                }
                                else
                                {
                                    //XmlSchemaComplexContent complexContent = (XmlSchemaComplexContent)xsct.ContentModel;
                                    if (xsct.ContentModel is XmlSchemaComplexContent)
                                    {
                                        Logger.Text += "Complex; ";
                                    }
                                }
                                Logger.Text += "\',";
                            }
                        }
                    }
                    Logger.Text += "\r\n";
                }

                ports        = servdesc.PortTypes;
                Logger.Text += " *** Found " + ports.Count + " portType(s) *** \r\n";
                TreeNode tn      = null;
                TreeNode msgNode = null;
                TreeNode root    = new TreeNode(urltext.Text);
                treeView1.Nodes.Add(root);
                for (int j = 0; j < ports.Count; j++)
                {
                    ops          = ports[j].Operations;
                    Logger.Text += " --- Found " + ops.Count + " operation(s) in : " + (j + 1) + " ---\r\n";
                    for (int i = 0; i < ops.Count; i++)
                    {
                        Logger.Text += ops[i].Name + "->" + "\r\n";
                        tn           = new TreeNode(ops[i].Name);
                        root.Nodes.Add(tn);
                        System.Web.Services.Description.OperationMessageCollection iter = ops[i].Messages;
                        //Message msgiter = null;
                        for (int k = 0; k < iter.Count; k++)
                        {
                            Logger.Text += iter[k].Message.Name + "\r\n";
                            msgNode      = new TreeNode(iter[k].Message.Name);
                            tn.Nodes.Add(msgNode);
                        }
                    }
                }
                GenerateSOAP();

                /*
                 * while (xmlr.Read())
                 * {
                 *  switch (xmlr.NodeType)
                 *  {
                 *      case XmlNodeType.Element:
                 *
                 *          Logger.Text += xmlr.Name + "->" + xmlr.R + "\r\n";
                 *          break;
                 *      case XmlNodeType.EndElement:
                 *          break;
                 *      default:
                 *          break;
                 *  }
                 * }
                 */
            }
            catch (XmlException xe)
            {
                Logger.Text += xe.StackTrace;
            }

            catch (Exception ex)
            {
                Logger.Text += ex.StackTrace;
            }
            finally
            {
                if (xmlr != null)
                {
                    xmlr.Close();
                }
            }
        }
Example #3
0
        private TypeModel CreateTypeModel(Uri source, XmlSchemaComplexType complexType, NamespaceModel namespaceModel, XmlQualifiedName qualifiedName, List <DocumentationModel> docs)
        {
            var name = _configuration.NamingProvider.ComplexTypeNameFromQualifiedName(qualifiedName);

            if (namespaceModel != null)
            {
                name = namespaceModel.GetUniqueTypeName(name);
            }

            var classModel = new ClassModel(_configuration)
            {
                Name           = name,
                Namespace      = namespaceModel,
                XmlSchemaName  = qualifiedName,
                XmlSchemaType  = complexType,
                IsAbstract     = complexType.IsAbstract,
                IsAnonymous    = string.IsNullOrEmpty(complexType.QualifiedName.Name),
                IsMixed        = complexType.IsMixed,
                IsSubstitution = complexType.Parent is XmlSchemaElement && !((XmlSchemaElement)complexType.Parent).SubstitutionGroup.IsEmpty
            };

            classModel.Documentation.AddRange(docs);

            if (namespaceModel != null)
            {
                namespaceModel.Types[classModel.Name] = classModel;
            }

            if (!qualifiedName.IsEmpty)
            {
                var key = BuildKey(complexType, qualifiedName);
                Types[key] = classModel;
            }

            if (complexType.BaseXmlSchemaType != null && complexType.BaseXmlSchemaType.QualifiedName != AnyType)
            {
                var baseModel = CreateTypeModel(source, complexType.BaseXmlSchemaType, complexType.BaseXmlSchemaType.QualifiedName);
                classModel.BaseClass = baseModel;
                if (baseModel is ClassModel baseClassModel)
                {
                    baseClassModel.DerivedTypes.Add(classModel);
                }
            }

            XmlSchemaParticle particle = null;

            if (classModel.BaseClass != null)
            {
                if (complexType.ContentModel.Content is XmlSchemaComplexContentExtension complexContent)
                {
                    particle = complexContent.Particle;
                }

                // If it's a restriction, do not duplicate elements on the derived class, they're already in the base class.
                // See https://msdn.microsoft.com/en-us/library/f3z3wh0y.aspx
            }
            else
            {
                particle = complexType.Particle ?? complexType.ContentTypeParticle;
            }

            var items = GetElements(particle, complexType).ToList();

            if (_configuration.GenerateInterfaces)
            {
                var interfaces = items.Select(i => i.XmlParticle).OfType <XmlSchemaGroupRef>()
                                 .Select(i => (InterfaceModel)CreateTypeModel(CodeUtilities.CreateUri(i.SourceUri), Groups[i.RefName], i.RefName)).ToList();

                classModel.AddInterfaces(interfaces);
            }

            var properties = CreatePropertiesForElements(source, classModel, particle, items);

            classModel.Properties.AddRange(properties);

            XmlSchemaObjectCollection attributes = null;

            if (classModel.BaseClass != null)
            {
                if (complexType.ContentModel.Content is XmlSchemaComplexContentExtension complexContent)
                {
                    attributes = complexContent.Attributes;
                }
                else if (complexType.ContentModel.Content is XmlSchemaSimpleContentExtension simpleContent)
                {
                    attributes = simpleContent.Attributes;
                }

                // If it's a restriction, do not duplicate attributes on the derived class, they're already in the base class.
                // See https://msdn.microsoft.com/en-us/library/f3z3wh0y.aspx
            }
            else
            {
                attributes = complexType.Attributes;
            }

            if (attributes != null)
            {
                var attributeProperties = CreatePropertiesForAttributes(source, classModel, attributes.Cast <XmlSchemaObject>());
                classModel.Properties.AddRange(attributeProperties);

                if (_configuration.GenerateInterfaces)
                {
                    var attributeInterfaces = attributes.OfType <XmlSchemaAttributeGroupRef>()
                                              .Select(i => (InterfaceModel)CreateTypeModel(CodeUtilities.CreateUri(i.SourceUri), AttributeGroups[i.RefName], i.RefName));
                    classModel.AddInterfaces(attributeInterfaces);
                }
            }

            if (complexType.AnyAttribute != null)
            {
                var property = new PropertyModel(_configuration)
                {
                    OwningType = classModel,
                    Name       = "AnyAttribute",
                    Type       = new SimpleModel(_configuration)
                    {
                        ValueType = typeof(XmlAttribute), UseDataTypeAttribute = false
                    },
                    IsAttribute  = true,
                    IsCollection = true,
                    IsAny        = true
                };

                var attributeDocs = GetDocumentation(complexType.AnyAttribute);
                property.Documentation.AddRange(attributeDocs);

                classModel.Properties.Add(property);
            }

            return(classModel);
        }
        private void WriteFacets(XmlSchemaObjectCollection facets)
        {
            if (facets == null)
            {
                return;
            }

            ArrayList a = new ArrayList();

            for (int i = 0; i < facets.Count; i++)
            {
                a.Add(facets[i]);
            }
            a.Sort(new XmlFacetComparer());
            for (int ia = 0; ia < a.Count; ia++)
            {
                XmlSchemaObject ai = (XmlSchemaObject)a[ia];
                if (ai is XmlSchemaMinExclusiveFacet)
                {
                    Write_XmlSchemaFacet("minExclusive", (XmlSchemaFacet)ai);
                }
                else if (ai is XmlSchemaMaxInclusiveFacet)
                {
                    Write_XmlSchemaFacet("maxInclusive", (XmlSchemaFacet)ai);
                }
                else if (ai is XmlSchemaMaxExclusiveFacet)
                {
                    Write_XmlSchemaFacet("maxExclusive", (XmlSchemaFacet)ai);
                }
                else if (ai is XmlSchemaMinInclusiveFacet)
                {
                    Write_XmlSchemaFacet("minInclusive", (XmlSchemaFacet)ai);
                }
                else if (ai is XmlSchemaLengthFacet)
                {
                    Write_XmlSchemaFacet("length", (XmlSchemaFacet)ai);
                }
                else if (ai is XmlSchemaEnumerationFacet)
                {
                    Write_XmlSchemaFacet("enumeration", (XmlSchemaFacet)ai);
                }
                else if (ai is XmlSchemaMinLengthFacet)
                {
                    Write_XmlSchemaFacet("minLength", (XmlSchemaFacet)ai);
                }
                else if (ai is XmlSchemaPatternFacet)
                {
                    Write_XmlSchemaFacet("pattern", (XmlSchemaFacet)ai);
                }
                else if (ai is XmlSchemaTotalDigitsFacet)
                {
                    Write_XmlSchemaFacet("totalDigits", (XmlSchemaFacet)ai);
                }
                else if (ai is XmlSchemaMaxLengthFacet)
                {
                    Write_XmlSchemaFacet("maxLength", (XmlSchemaFacet)ai);
                }
                else if (ai is XmlSchemaWhiteSpaceFacet)
                {
                    Write_XmlSchemaFacet("whiteSpace", (XmlSchemaFacet)ai);
                }
                else if (ai is XmlSchemaFractionDigitsFacet)
                {
                    Write_XmlSchemaFacet("fractionDigit", (XmlSchemaFacet)ai);
                }
            }
        }
Example #5
0
        private void InitializeChildren(XmlSchemaComplexType complexType, SimplifiedSchemaObject element, bool initializingComplexType)
        {
            if (complexType == null)
            {
                return;
            }

            XmlSchemaComplexContentRestriction restriction = complexType.ContentModel != null ? complexType.ContentModel.Content as XmlSchemaComplexContentRestriction : null;
            XmlSchemaComplexContentExtension   extension   = complexType.ContentModel != null ? complexType.ContentModel.Content as XmlSchemaComplexContentExtension : null;

            XmlSchemaObjectCollection baseAttributes = null;

            if (restriction != null)
            {
                baseAttributes = restriction.Attributes;
            }
            else if (extension != null)
            {
                baseAttributes = extension.Attributes;
            }

            if (baseAttributes != null)
            {
                foreach (XmlSchemaObject cObject in baseAttributes)
                {
                    XmlSchemaAttribute cAttribute = cObject as XmlSchemaAttribute;

                    if (cAttribute != null)
                    {
                        element.Children.Add(
                            new SimplifiedSchemaObject(element, cAttribute));
                    }
                }
            }

            foreach (XmlSchemaObject cObject in complexType.Attributes)
            {
                XmlSchemaAttribute cAttribute = cObject as XmlSchemaAttribute;

                if (cAttribute != null)
                {
                    element.Children.Add(
                        new SimplifiedSchemaObject(element, cAttribute));
                }
            }

            //if (element.ToString() == "ClinicalDocument/recordTarget/patientRole")
            //    Console.WriteLine("Test");

            if (complexType.ContentTypeParticle is XmlSchemaSequence)
            {
                XmlSchemaSequence sequence = complexType.ContentTypeParticle as XmlSchemaSequence;

                foreach (XmlSchemaObject cObject in sequence.Items)
                {
                    // Check here if this element's name is the same as it's parent or grand-parents
                    XmlSchemaElement cElement = cObject as XmlSchemaElement;
                    XmlSchemaChoice  cChoice  = cObject as XmlSchemaChoice;

                    if (cElement != null)
                    {
                        InitializeLevel(element, cElement, initializingComplexType);
                    }
                    else if (cChoice != null)
                    {
                        foreach (XmlSchemaObject cChoiceObject in cChoice.Items)
                        {
                            XmlSchemaElement cChoiceElement = cChoiceObject as XmlSchemaElement;

                            if (cChoiceElement != null)
                            {
                                InitializeLevel(element, cChoiceElement, initializingComplexType);
                            }
                        }
                    }
                }
            }
        }
Example #6
0
        public static void WriteIntroductionForObject(this MamlWriter writer,
                                                      Context context, XmlSchemaObject obj)
        {
            DocumentationInfo documentationInfo =
                context.DocumentationManager.GetObjectDocumentationInfo(obj);

            writer.StartIntroduction();
            writer.WriteSummary(documentationInfo);
            if (context.Configuration.IncludeAutoOutline)
            {
                XmlSchemaAttribute      attribute;
                XmlSchemaElement        element;
                XmlSchemaGroup          group;
                XmlSchemaAttributeGroup attributeGroup;
                XmlSchemaSimpleType     simpleType;
                XmlSchemaComplexType    complexType;

                if (Casting.TryCast(obj, out element))
                {
                    bool isSimpleType = element.ElementSchemaType is XmlSchemaSimpleType;
                    if (!isSimpleType)
                    {
                        writer.StartParagraph();
                        writer.WriteToken("autoOutline");
                        writer.EndParagraph();

                        context.MoveToTopLink = true;
                    }
                }
                else if (Casting.TryCast(obj, out attribute))
                {
                }
                else if (Casting.TryCast(obj, out group))
                {
                    XmlSchemaGroupBase compositor = group.Particle;
                    if (compositor != null)
                    {
                        XmlSchemaObjectCollection items = compositor.Items;
                        if (items != null && items.Count > 3)
                        {
                            writer.StartParagraph();
                            writer.WriteToken("autoOutline");
                            writer.EndParagraph();

                            context.MoveToTopLink = true;
                        }
                    }
                }
                else if (Casting.TryCast(obj, out attributeGroup))
                {
                }
                else if (Casting.TryCast(obj, out simpleType))
                {
                }
                else if (Casting.TryCast(obj, out complexType))
                {
                    if (complexType.ContentType != XmlSchemaContentType.Empty &&
                        complexType.ContentType != XmlSchemaContentType.TextOnly)
                    {
                        writer.StartParagraph();
                        writer.WriteToken("autoOutline");
                        writer.EndParagraph();

                        context.MoveToTopLink = true;
                    }
                }
            }
            writer.WriteObsoleteInfo(context, obj);
            writer.WriteNamespaceAndSchemaInfo(context, obj);
            writer.EndIntroduction();
        }
Example #7
0
        private static IPluglet ParseComplexType(IPluglet parent, XmlSchemaComplexType ct, XmlSchema schema)
        {
            //Console.WriteLine("ParseComplexType.. " + ct.Name);
            IPluglet ret = null;
            XmlSchemaObjectCollection elementC = null;
            XmlSchemaObjectCollection attribC  = ct.Attributes;

            //Schemas should have elements only. A migration tool is ready which can take
            //a schema containing attributes and elements and convert it to an elements only
            //schema
            if (attribC != null && attribC.Count > 0)
            {
                foreach (XmlSchemaAttribute attr in attribC)
                {
                    string attributeName = "{" + attr.Name + "}";

                    int minOccurs = 0;
                    int maxOccurs = 1;
                    if (attr.Use.Equals(XmlSchemaUse.Required))
                    {
                        minOccurs = 1;
                    }
                    string description = string.Empty;
                    parent.Attributes.Add(new Pluglet(attributeName, description, PlugletType.Data, parent, minOccurs, maxOccurs));
                }
            }

            if (ct.ContentModel != null)
            {
                AppendSchemaError("SchemaCode105EUnexpectedContentModelFound");
            }

            if (ct.ContentModel == null && ct.Particle != null)
            {
                if (ct.Particle is XmlSchemaSequence)
                {
                    elementC = (ct.Particle as XmlSchemaGroupBase).Items;
                }
                else if (ct.Particle is XmlSchemaChoice)
                {
                    elementC = (ct.Particle as XmlSchemaChoice).Items;
                    //AppendSchemaError("SchemaCode128EXmlSchemaChoiceParentChoiceNotFound");
                }
                else if (ct.Particle is XmlSchemaAll)
                {
                    AppendSchemaError("SchemaCode126EXmlSchemaAllParentAllNotFound");
                }
                else
                {
                    AppendSchemaError("SchemaCode106EXmlSchemaGroupNotFound");
                }
            }

            if (elementC != null)
            {
                foreach (XmlSchemaObject o in elementC)
                {
                    ret = ParseElement(parent, (XmlSchemaElement)o, schema);
                }
            }

            return(ret);
        }
            protected XmlSchemaComplexType FindOrCreateComplexType(Type t)
            {
                XmlSchemaComplexType ct;
                string typeId = GenerateIDFromType(t);

                ct = FindComplexTypeByID(typeId);
                if (ct != null)
                {
                    return(ct);
                }

                ct      = new XmlSchemaComplexType();
                ct.Name = typeId;

                // add complex type to collection immediately to avoid stack
                // overflows, when we allow a type to be nested
                _nantComplexTypes.Add(typeId, ct);

#if NOT_IMPLEMENTED
                //
                // TODO - add task/type documentation in the future
                //

                ct.Annotation = new XmlSchemaAnnotation();
                XmlSchemaDocumentation doc = new XmlSchemaDocumentation();
                ct.Annotation.Items.Add(doc);
                doc.Markup = ...;
#endif

                XmlSchemaSequence         group1 = null;
                XmlSchemaObjectCollection attributesCollection = ct.Attributes;

                foreach (MemberInfo memInfo in t.GetMembers(BindingFlags.Instance | BindingFlags.Public))
                {
                    if (memInfo.DeclaringType.Equals(typeof(object)))
                    {
                        continue;
                    }

                    //Check for any return type that is derived from Element

                    // add Attributes
                    TaskAttributeAttribute taskAttrAttr = (TaskAttributeAttribute)
                                                          Attribute.GetCustomAttribute(memInfo, typeof(TaskAttributeAttribute),
                                                                                       false);
                    BuildElementAttribute buildElemAttr = (BuildElementAttribute)
                                                          Attribute.GetCustomAttribute(memInfo, typeof(BuildElementAttribute),
                                                                                       false);

                    if (taskAttrAttr != null)
                    {
                        XmlSchemaAttribute newAttr = CreateXsdAttribute(taskAttrAttr.Name, taskAttrAttr.Required);
                        attributesCollection.Add(newAttr);
                    }
                    else if (buildElemAttr != null)
                    {
                        // Create individial choice for any individual child Element
                        Decimal min = 0;

                        if (buildElemAttr.Required)
                        {
                            min = 1;
                        }

                        XmlSchemaElement childElement = new XmlSchemaElement();
                        childElement.MinOccurs = min;
                        childElement.MaxOccurs = 1;
                        childElement.Name      = buildElemAttr.Name;

                        //XmlSchemaGroupBase elementGroup = CreateXsdSequence(min, Decimal.MaxValue);

                        Type childType;

                        // We will only process child elements if they are defined for Properties or Fields, this should be enforced by the AttributeUsage on the Attribute class
                        if (memInfo is PropertyInfo)
                        {
                            childType = ((PropertyInfo)memInfo).PropertyType;
                        }
                        else if (memInfo is FieldInfo)
                        {
                            childType = ((FieldInfo)memInfo).FieldType;
                        }
                        else if (memInfo is MethodInfo)
                        {
                            MethodInfo method = (MethodInfo)memInfo;
                            if (method.GetParameters().Length == 1)
                            {
                                childType = method.GetParameters()[0].ParameterType;
                            }
                            else
                            {
                                throw new ApplicationException("Method should have one parameter.");
                            }
                        }
                        else
                        {
                            throw new ApplicationException("Member Type != Field/Property/Method");
                        }

                        BuildElementArrayAttribute buildElementArrayAttribute = (BuildElementArrayAttribute)
                                                                                Attribute.GetCustomAttribute(memInfo, typeof(BuildElementArrayAttribute), false);

                        // determine type of child elements

                        if (buildElementArrayAttribute != null)
                        {
                            if (buildElementArrayAttribute.ElementType == null)
                            {
                                if (childType.IsArray)
                                {
                                    childType = childType.GetElementType();
                                }
                                else
                                {
                                    Type elementType = null;

                                    // locate Add method with 1 parameter, type of that parameter is parameter type
                                    foreach (MethodInfo method in childType.GetMethods(BindingFlags.Public | BindingFlags.Instance))
                                    {
                                        if (method.Name == "Add" && method.GetParameters().Length == 1)
                                        {
                                            ParameterInfo parameter = method.GetParameters()[0];
                                            elementType = parameter.ParameterType;
                                            break;
                                        }
                                    }

                                    childType = elementType;
                                }
                            }
                            else
                            {
                                childType = buildElementArrayAttribute.ElementType;
                            }

                            if (childType == null || !typeof(Element).IsAssignableFrom(childType))
                            {
                                throw new BuildException(string.Format(CultureInfo.InvariantCulture,
                                                                       ResourceUtils.GetString("NA1140"), memInfo.DeclaringType.FullName, memInfo.Name));
                            }
                        }

                        BuildElementCollectionAttribute buildElementCollectionAttribute = (BuildElementCollectionAttribute)Attribute.GetCustomAttribute(memInfo, typeof(BuildElementCollectionAttribute), false);
                        if (buildElementCollectionAttribute != null)
                        {
                            XmlSchemaComplexType collectionType = new XmlSchemaComplexType();
                            XmlSchemaSequence    sequence       = new XmlSchemaSequence();
                            collectionType.Particle = sequence;

                            sequence.MinOccurs       = 0;
                            sequence.MaxOccursString = "unbounded";

                            XmlSchemaElement itemType = new XmlSchemaElement();
                            itemType.Name           = buildElementCollectionAttribute.ChildElementName;
                            itemType.SchemaTypeName = FindOrCreateComplexType(childType).QualifiedName;

                            sequence.Items.Add(itemType);

                            childElement.SchemaType = collectionType;
                        }
                        else
                        {
                            childElement.SchemaTypeName = FindOrCreateComplexType(childType).QualifiedName;
                        }

                        // lazy init of sequence
                        if (group1 == null)
                        {
                            group1      = CreateXsdSequence(0, Decimal.MaxValue);
                            ct.Particle = group1;
                        }

                        group1.Items.Add(childElement);
                    }
                }

                // allow attributes from other namespace
                ct.AnyAttribute                 = new XmlSchemaAnyAttribute();
                ct.AnyAttribute.Namespace       = "##other";
                ct.AnyAttribute.ProcessContents = XmlSchemaContentProcessing.Skip;

                Schema.Items.Add(ct);
                Compile();

                return(ct);
            }
Example #9
0
        // recursive decoder
        private XSDTreeNode DecodeSchema2(XmlSchemaObject obj, XSDTreeNode node)
        {
            XSDTreeNode newNode = node;

            // convert the object to all types and then check what type actually exists
            XmlSchemaAnnotation    annot       = obj as XmlSchemaAnnotation;
            XmlSchemaAttribute     attrib      = obj as XmlSchemaAttribute;
            XmlSchemaFacet         facet       = obj as XmlSchemaFacet;
            XmlSchemaDocumentation doc         = obj as XmlSchemaDocumentation;
            XmlSchemaAppInfo       appInfo     = obj as XmlSchemaAppInfo;
            XmlSchemaElement       element     = obj as XmlSchemaElement;
            XmlSchemaSimpleType    simpleType  = obj as XmlSchemaSimpleType;
            XmlSchemaComplexType   complexType = obj as XmlSchemaComplexType;

            // if annotation, add a tree node and recurse for documentation and app info
            if (annot != null)
            {
                newNode = new XSDTreeNode("--annotation--", "--annotation--", false);
                node.Add(newNode);
                foreach (XmlSchemaObject schemaObject in annot.Items)
                {
                    DecodeSchema2(schemaObject, newNode);
                }
            }
            // if attribute, add an attribute at tree node
            else if (attrib != null)
            {
                node.AddAttribute(attrib.QualifiedName.Name, attrib.SchemaTypeName.Name);
            }
            // if facet, add a tree node
            else if (facet != null)
            {
                newNode = new XSDTreeNode(facet.ToString(), facet.ToString(), false);
                node.Add(newNode);
            }
            // if documentation, add a tree node
            else if (doc != null)
            {
                newNode = new XSDTreeNode("--documentation--", "--documentation--", false);
                node.Add(newNode);
            }
            // if app info, add a tree node
            else if (appInfo != null)
            {
                newNode = new XSDTreeNode("--app info--", "--app info--", false);
                node.Add(newNode);
            }
            // if an element, determine whether the element is a simple type or a complex type
            else if (element != null)
            {
                XmlSchemaSimpleType  st = element.SchemaType as XmlSchemaSimpleType;
                XmlSchemaComplexType ct = element.SchemaType as XmlSchemaComplexType;

                if (st != null)
                {
                    // this is a simple type element.  Recurse.
                    XSDTreeNode node2 = DecodeSchema2(st, newNode);
                    node2.Name        = element.Name;
                    node2.Element     = true;
                    node2.ComplexType = false;
                }
                else if (ct != null)
                {
                    // this is a complex type element.  Recurse.
                    XSDTreeNode node2 = DecodeSchema2(ct, newNode);
                    newNode.Remove(node2);
                    node2.Name        = element.Name;
                    node2.Element     = true;
                    node2.ComplexType = true;
                    newNode.Add(node2);
                }
                else
                {
                    // This is a plain ol' fashioned element.
                    newNode         = new XSDTreeNode(element.QualifiedName.Name, element.ElementSchemaType?.Name ?? element.SchemaTypeName.Name, false);
                    newNode.Element = true;
                    node.Add(newNode);
                }
            }
            // if a simple type, then add a tree node and recurse facets
            else if (simpleType != null)
            {
                newNode = new XSDTreeNode(simpleType.QualifiedName.Name, simpleType.BaseXmlSchemaType.Name, false);
                node.Add(newNode);
                XmlSchemaSimpleTypeRestriction rest = simpleType.Content as XmlSchemaSimpleTypeRestriction;
                if (rest != null)
                {
                    foreach (XmlSchemaFacet schemaObject in rest.Facets)
                    {
                        DecodeSchema2(schemaObject, newNode);
                    }
                }
            }
            // if a complex type, add a tree node and recurse its sequence
            else if (complexType != null)
            {
                if (null == complexType.Name)
                {
                    newNode = new XSDTreeNode("--tmp-name--", complexType.BaseXmlSchemaType.Name, true);
                }
                else
                {
                    newNode = new XSDTreeNode(complexType.Name, complexType.BaseXmlSchemaType.Name, true);
                }

                node.Add(newNode);

                XmlSchemaSequence seq = complexType.Particle as XmlSchemaSequence;
                if (seq != null)
                {
                    foreach (XmlSchemaObject schemaObject in seq.Items)
                    {
                        DecodeSchema2(schemaObject, newNode);
                    }
                }
            }

            // now recurse any object collection of the type.
            foreach (PropertyInfo property in obj.GetType().GetProperties())
            {
                if (property.PropertyType.FullName == "System.Xml.Schema.XmlSchemaObjectCollection")
                {
                    XmlSchemaObjectCollection childObjectCollection = (XmlSchemaObjectCollection)property.GetValue(obj, null);
                    foreach (XmlSchemaObject schemaObject in childObjectCollection)
                    {
                        DecodeSchema2(schemaObject, newNode);
                    }
                }
            }
            return(newNode);
        }
Example #10
0
        private static string ReadDocumentationFromElement(XmlSchemaElement elem, bool isField, out Dictionary <string, string> pairs)
        {
            pairs = new Dictionary <string, string>(5);
            XmlSchemaAnnotation annotation = elem.Annotation;
            string reference = string.Empty;

            if (annotation != null && annotation.Items != null)
            {
                XmlSchemaObjectCollection coll = annotation.Items;
                foreach (XmlSchemaObject obj in coll)
                {
                    if (obj is XmlSchemaAppInfo)
                    {
                        XmlSchemaAppInfo appInfo = (XmlSchemaAppInfo)obj;
                        XmlNode[]        node    = appInfo.Markup;
                        if (node != null)
                        {
                            for (int i = 0; i < node.Length; i++)
                            {
                                XmlElement element = node[i] as XmlElement;
                                if (element != null)
                                {
                                    if (string.Compare(element.LocalName, "STD_info", StringComparison.OrdinalIgnoreCase) == 0)
                                    {
                                        string data = element.GetAttribute("Name");
                                        if (!string.IsNullOrEmpty(data))
                                        {
                                            pairs["Name"] = data;
                                        }

                                        data = element.GetAttribute("Number");
                                        if (!string.IsNullOrEmpty(data))
                                        {
                                            pairs["Number"] = data;
                                        }

                                        data = element.GetAttribute("DataType");
                                        if (!string.IsNullOrEmpty(data))
                                        {
                                            pairs["DataType"] = data;
                                        }

                                        data = element.GetAttribute("MaximumLength");
                                        if (!string.IsNullOrEmpty(data))
                                        {
                                            pairs["MaximumLength"] = data;
                                        }

                                        data = element.GetAttribute("MinimumLength");
                                        if (!string.IsNullOrEmpty(data))
                                        {
                                            pairs["MinimumLength"] = data;
                                        }
                                    }
                                }

                                /*
                                 * if (node[i].NamespaceURI == "http://schemas.microsoft.com/BizTalk/2003"
                                 *  && ((node[i].LocalName == "recordInfo" && !isField) || (node[i].LocalName == "fieldInfo" && isField))
                                 *  && node[i] is XmlElement)
                                 * {
                                 *  reference = (node[i] as XmlElement).GetAttribute("notes");
                                 *  pairs["notes"] = reference;
                                 *  if (!string.IsNullOrEmpty(reference)) break;
                                 * }
                                 */
                            }
                        }
                    }

                    else if (obj is XmlSchemaDocumentation)
                    {
                        XmlSchemaDocumentation doc = (XmlSchemaDocumentation)obj;
                        XmlNode[] node             = doc.Markup;
                        if (node != null)
                        {
                            for (int i = 0; i < node.Length; i++)
                            {
                                if (node[i] is XmlText)
                                {
                                    reference = (node[i] as XmlText).InnerText;
                                    pairs["Documentation"] = reference;
                                    break;
                                }
                            }
                        }
                    }
                }
            }

            return(reference);
        }
Example #11
0
 public virtual void EndProcessing(XmlSchemaObjectCollection obj)
 {
 }
Example #12
0
 public virtual bool StartProcessing(XmlSchemaObjectCollection obj)
 {
     return(true);
 }
Example #13
0
        /* For methods documentation's see the IField interface */

        public Control GetWebControl(System.Web.HttpServerUtility server, XmlNode renderingDocument)
        {
            string tip = (renderingDocument.Attributes["description"] == null) ?
                         "" : renderingDocument.Attributes["description"].Value.FromXmlValue2Render(server);

            PlaceHolder ph = new PlaceHolder();

            Label lbl = new Label();

            if (renderingDocument.Attributes["renderedLabel"] != null)
            {
                lbl.Text = renderingDocument.Attributes["renderedLabel"].Value.FromXmlValue2Render(server);
            }
            else
            {
                lbl.Text = this.Name.FromXmlName2Render(server);
            }
            lbl.CssClass = "label";
            lbl.ToolTip  = tip;
            ph.Controls.Add(lbl);

            DateBoxControl dbox = new DateBoxControl(this);

            dbox.ToolTip = tip;

            if (renderingDocument.Attributes["class"] != null)
            {
                dbox.tbox.CssClass = renderingDocument.Attributes["class"].Value.FromXmlValue2Render(server);
            }
            if (renderingDocument.Attributes["rel"] != null)
            {
                dbox.tbox.Attributes.Add("rel", renderingDocument.Attributes["rel"].Value.FromXmlValue2Render(server));
            }

            ph.Controls.Add(dbox);

            // --- ADD VALIDATORS ---


            RegularExpressionValidator rev = new RegularExpressionValidator();

            rev.Display           = ValidatorDisplay.Dynamic;
            rev.ControlToValidate = dbox.ID + "$" + dbox.tbox.ID;
            rev.ErrorMessage      = "A value isn't a valid date (format: gg/mm/yyyy)";
            const string REgg = "([1-9]|0[1-9]|[12][0-9]|3[01])";
            const string REmm = "([1-9]|0[1-9]|1[012])";
            const string REyy = "[0-9]{4}";
            const string sep  = "[/.-]";

            rev.ValidationExpression = "^" + REgg + sep + REmm + sep + REyy + "$";
            rev.ValidationGroup      = "1";
            ph.Controls.Add(rev);

            if (!Common.getElementFromSchema(baseSchema).IsNillable)
            {
                RequiredFieldValidator rqfv = new RequiredFieldValidator();
                rqfv.ErrorMessage      = "Required fields shouldn't be empty";
                rqfv.ControlToValidate = dbox.ID + "$" + dbox.tbox.ID;
                rqfv.ValidationGroup   = "1";
                rqfv.Display           = ValidatorDisplay.Dynamic;
                ph.Controls.Add(rqfv);
            }


            if (((XmlSchemaSimpleType)Common.getElementFromSchema(baseSchema).SchemaType) == null)
            {
                return(ph);
            }
            XmlSchemaObjectCollection constrColl =
                ((XmlSchemaSimpleTypeRestriction)
                 ((XmlSchemaSimpleType)
                  Common.getElementFromSchema(baseSchema)
                  .SchemaType).Content).Facets;


            foreach (XmlSchemaFacet facet in constrColl)
            {
                if (facet is XmlSchemaMinInclusiveFacet)
                {
                    RangeValidator rv = new RangeValidator();
                    rv.Type              = ValidationDataType.Date;
                    rv.MinimumValue      = DateTime.Parse(facet.Value).ToString().Substring(0, 10);
                    rv.ErrorMessage      = "Date must be equal or later than " + DateTime.Parse(facet.Value).ToString(CultureInfo.CurrentCulture.DateTimeFormat).Substring(0, 10);
                    rv.MaximumValue      = DateTime.MaxValue.ToString().Substring(0, 10);
                    rv.ControlToValidate = dbox.ID + "$" + dbox.tbox.ID;
                    rv.Display           = ValidatorDisplay.Dynamic;
                    rv.ValidationGroup   = "1";
                    ph.Controls.Add(rv);
                }
                if (facet is XmlSchemaMaxInclusiveFacet)
                {
                    RangeValidator rv = new RangeValidator();
                    rv.Type              = ValidationDataType.Date;
                    rv.MaximumValue      = DateTime.Parse(facet.Value).ToString().Substring(0, 10);
                    rv.ErrorMessage      = "Date must be equal or previous to " + DateTime.Parse(facet.Value).ToString(CultureInfo.CurrentCulture.DateTimeFormat).Substring(0, 10);
                    rv.MinimumValue      = DateTime.MinValue.ToString().Substring(0, 10);
                    rv.ControlToValidate = dbox.ID + "$" + dbox.tbox.ID;
                    rv.Display           = ValidatorDisplay.Dynamic;
                    rv.ValidationGroup   = "1";
                    ph.Controls.Add(rv);
                }
            }
            return(ph);
        }
Example #14
0
 internal virtual void OnRemove(XmlSchemaObjectCollection container, object item) {}
Example #15
0
        public Control GetWebControl(System.Web.HttpServerUtility server, XmlNode renderingDocument)
        {
            PlaceHolder ph = new PlaceHolder();

            Label lbl = new Label();

            if (renderingDocument.Attributes["renderedLabel"] != null)
            {
                lbl.Text = renderingDocument.Attributes["renderedLabel"].Value.FromXmlValue2Render(server);
            }
            else
            {
                lbl.Text = this.Name.FromXmlName2Render(server);
            }
            lbl.CssClass = "label";
            ph.Controls.Add(lbl);

            StringBoxControl sbox = new StringBoxControl(this);

            //sbox.CausesValidation = false;

            if (renderingDocument.Attributes["class"] != null)
            {
                sbox.CssClass = renderingDocument.Attributes["class"].Value.FromXmlValue2Render(server);
            }
            if (renderingDocument.Attributes["rel"] != null)
            {
                sbox.Attributes.Add("rel", renderingDocument.Attributes["rel"].Value.FromXmlValue2Render(server));
            }
            if (renderingDocument.Attributes["description"] != null)
            {
                sbox.ToolTip = renderingDocument.Attributes["description"].Value.FromXmlValue2Render(server);
            }

            // Setting properties
            sbox.TextMode = TextBoxMode.SingleLine;
            if (renderingDocument.Attributes["rows"] != null)
            {
                string ns = renderingDocument.Attributes["rows"].Value.FromXmlValue2Render(server);
                int    n;
                if (int.TryParse(ns, out n) && n > 1)
                {
                    sbox.TextMode = TextBoxMode.MultiLine;
                    sbox.Rows     = n;
                }
            }
            if (renderingDocument.Attributes["hiddentext"] != null)
            {
                if (renderingDocument.Attributes["hiddentext"].Value.FromXmlValue2Render(server).ToLower().Equals("true"))
                {
                    sbox.TextMode = TextBoxMode.Password;
                }
            }


            ph.Controls.Add(sbox);

            //--- ADD validators ---

            if (!Common.getElementFromSchema(baseSchema).IsNillable)
            {
                RequiredFieldValidator rqfv = new RequiredFieldValidator();
                rqfv.ErrorMessage      = "Required fields shouldn't be empty";
                rqfv.ControlToValidate = sbox.ID;
                rqfv.Display           = ValidatorDisplay.Dynamic;
                rqfv.ValidationGroup   = "1";
                ph.Controls.Add(rqfv);
            }

            if (((XmlSchemaSimpleType)Common.getElementFromSchema(baseSchema).SchemaType) == null)
            {
                return(ph);
            }

            XmlSchemaObjectCollection constrColl =
                ((XmlSchemaSimpleTypeRestriction)((XmlSchemaSimpleType)Common.getElementFromSchema(baseSchema).SchemaType).Content).Facets;

            // Set validators from XSD
            foreach (XmlSchemaFacet facet in constrColl)
            {
                if (facet is XmlSchemaMaxLengthFacet)
                {
                    ph.Controls.Add(getMaxLengthValidator(Int32.Parse(facet.Value), sbox.ID));
                }
                else if (facet is XmlSchemaMinLengthFacet)
                {
                    ph.Controls.Add(getMinLengthValidator(Int32.Parse(facet.Value), sbox.ID));
                }
                else if (facet is XmlSchemaPatternFacet)
                {
                    ph.Controls.Add(getPatternValidator(facet.Value, sbox.ID));
                }
            }

            //---

            return(ph);
        }
Example #16
0
        /// <summary>
        /// Initializes a new instance of the <see cref="VEMap"/> class from a XMLSchema
        /// </summary>
        /// <param name="schema">The schema xml that describe the VEMap state.</param>
        public VEMap(XmlSchema schema, string name)
            : this()
        {
            this.Name = name;

            //Setting subtype name in the XSD
            //<xs:complexType name="VEMapN">
            ((XmlSchemaComplexType)baseSchema.Items[0]).Name = ((XmlSchemaComplexType)schema.Items[0]).Name;

            // Warning: I'll trust in the elements order

            // Check nillable elements
            List <XmlSchemaElement> schemaElements     = Common.getElementsFromSchema(schema);
            List <XmlSchemaElement> baseSchemaElements = Common.getElementsFromSchema(baseSchema);

            if (schemaElements[0].IsNillable)
            {
                baseSchemaElements[0].IsNillable = true;
            }
            if (schemaElements[1].IsNillable)
            {
                baseSchemaElements[1].IsNillable = true;
            }

            // adding latitude constraints
            if (((XmlSchemaSimpleType)schemaElements[0].SchemaType) != null)
            {
                XmlSchemaObjectCollection latConstrColl =
                    ((XmlSchemaSimpleTypeRestriction)
                     ((XmlSchemaSimpleType)
                      schemaElements[0]
                      .SchemaType).Content).Facets;

                foreach (XmlSchemaFacet facet in latConstrColl)
                {
                    Common.addFacet(facet, baseSchemaElements[0]);
                }
            }

            // adding longitude constraints
            if (((XmlSchemaSimpleType)schemaElements[1].SchemaType) != null)
            {
                XmlSchemaObjectCollection longConstrColl =
                    ((XmlSchemaSimpleTypeRestriction)
                     ((XmlSchemaSimpleType)
                      schemaElements[1]
                      .SchemaType).Content).Facets;

                foreach (XmlSchemaFacet facet in longConstrColl)
                {
                    Common.addFacet(facet, baseSchemaElements[1]);
                }
            }

            // adding custom constraints (close your eyes =)
            XmlSchemaComplexContentExtension cce =
                (XmlSchemaComplexContentExtension)(
                    (XmlSchemaComplexContent)(
                        ((XmlSchemaComplexType)
                         schema.Items[0])
                        ).ContentModel
                    ).Content;

            if (cce.Annotation != null)
            {
                foreach (XmlSchemaDocumentation sd in cce.Annotation.Items)
                {
                    if (sd.Markup[0].Name == "maxDistanceFrom")
                    {
                        AddMaxDistanceConstraint(sd.Markup[0].ChildNodes[0].InnerText, sd.Markup[0].ChildNodes[1].InnerText, sd.Markup[0].ChildNodes[2].InnerText);
                    }
                }
            }
        }
Example #17
0
        private static void EnumSchema(IAssociativeXmlObject parentAssociativeXmlObject, XmlSchemaObjectCollection currentXmlSchemaObjectCollection)
        {
            XmlSchemaElement     xmlSchemaElement;
            XmlSchemaComplexType xmlSchemaComplexType;
            XmlSchemaSequence    xmlSchemaSequence;
            XmlSchemaSimpleType  xmlSchemaSimpleType;
            ArrayConstruct       arrayConstruct00, arrayConstruct01;
            ObjectConstruct      objectConstruct00, objectConstruct01;
            PropertyConstruct    propertyConstruct00, propertyConstruct01;

            if ((object)parentAssociativeXmlObject == null)
            {
                throw new ArgumentNullException(nameof(parentAssociativeXmlObject));
            }

            if ((object)currentXmlSchemaObjectCollection == null)
            {
                throw new ArgumentNullException(nameof(currentXmlSchemaObjectCollection));
            }

            arrayConstruct00      = new ArrayConstruct();
            arrayConstruct00.Name = "XmlSchemaElements";
            parentAssociativeXmlObject.Items.Add(arrayConstruct00);

            foreach (XmlSchemaObject xmlSchemaObject in currentXmlSchemaObjectCollection)
            {
                objectConstruct00 = new ObjectConstruct();
                arrayConstruct00.Items.Add(objectConstruct00);

                xmlSchemaElement = xmlSchemaObject as XmlSchemaElement;

                if ((object)xmlSchemaElement != null)
                {
                    if (SolderFascadeAccessor.DataTypeFascade.IsNullOrWhiteSpace(xmlSchemaElement.Name) &&
                        !SolderFascadeAccessor.DataTypeFascade.IsNullOrWhiteSpace(xmlSchemaElement.RefName.Name))
                    {
                        propertyConstruct00          = new PropertyConstruct();
                        propertyConstruct00.Name     = "XmlSchemaElementIsRef";
                        propertyConstruct00.RawValue = true;
                        objectConstruct00.Items.Add(propertyConstruct00);

                        propertyConstruct00          = new PropertyConstruct();
                        propertyConstruct00.Name     = "XmlSchemaElementLocalName";
                        propertyConstruct00.RawValue = xmlSchemaElement.RefName.Name;
                        objectConstruct00.Items.Add(propertyConstruct00);

                        propertyConstruct00          = new PropertyConstruct();
                        propertyConstruct00.Name     = "XmlSchemaElementNamespace";
                        propertyConstruct00.RawValue = xmlSchemaElement.RefName.Namespace;
                        objectConstruct00.Items.Add(propertyConstruct00);

                        continue;
                    }
                    else
                    {
                        propertyConstruct00          = new PropertyConstruct();
                        propertyConstruct00.Name     = "XmlSchemaElementIsRef";
                        propertyConstruct00.RawValue = false;
                        objectConstruct00.Items.Add(propertyConstruct00);

                        propertyConstruct00          = new PropertyConstruct();
                        propertyConstruct00.Name     = "XmlSchemaElementLocalName";
                        propertyConstruct00.RawValue = xmlSchemaElement.QualifiedName.Name;
                        objectConstruct00.Items.Add(propertyConstruct00);

                        propertyConstruct00          = new PropertyConstruct();
                        propertyConstruct00.Name     = "XmlSchemaElementNamespace";
                        propertyConstruct00.RawValue = xmlSchemaElement.QualifiedName.Namespace;
                        objectConstruct00.Items.Add(propertyConstruct00);

                        xmlSchemaComplexType = xmlSchemaElement.ElementSchemaType as XmlSchemaComplexType;
                        xmlSchemaSimpleType  = xmlSchemaElement.ElementSchemaType as XmlSchemaSimpleType;

                        if ((object)xmlSchemaSimpleType != null)
                        {
                            propertyConstruct00          = new PropertyConstruct();
                            propertyConstruct00.Name     = "XmlSchemaElementSimpleType";
                            propertyConstruct00.RawValue = xmlSchemaSimpleType.Datatype.TypeCode;
                            objectConstruct00.Items.Add(propertyConstruct00);
                        }
                        else if ((object)xmlSchemaComplexType != null)
                        {
                            arrayConstruct01      = new ArrayConstruct();
                            arrayConstruct01.Name = "XmlSchemaAttributes";
                            objectConstruct00.Items.Add(arrayConstruct01);

                            if ((object)xmlSchemaComplexType.Attributes != null)
                            {
                                foreach (XmlSchemaAttribute xmlSchemaAttribute in xmlSchemaComplexType.Attributes)
                                {
                                    objectConstruct01 = new ObjectConstruct();
                                    arrayConstruct01.Items.Add(objectConstruct01);

                                    propertyConstruct01          = new PropertyConstruct();
                                    propertyConstruct01.Name     = "XmlSchemaElementLocalName";
                                    propertyConstruct01.RawValue = xmlSchemaAttribute.QualifiedName.Name;
                                    objectConstruct01.Items.Add(propertyConstruct01);

                                    propertyConstruct01          = new PropertyConstruct();
                                    propertyConstruct01.Name     = "XmlSchemaElementNamespace";
                                    propertyConstruct01.RawValue = xmlSchemaAttribute.QualifiedName.Namespace;
                                    objectConstruct01.Items.Add(propertyConstruct01);

                                    propertyConstruct01          = new PropertyConstruct();
                                    propertyConstruct01.Name     = "XmlSchemaElementNamespace";
                                    propertyConstruct01.RawValue = xmlSchemaAttribute.AttributeSchemaType.TypeCode;
                                    objectConstruct01.Items.Add(propertyConstruct01);
                                }
                            }

                            xmlSchemaSequence = xmlSchemaComplexType.ContentTypeParticle as XmlSchemaSequence;

                            if ((object)xmlSchemaSequence != null)
                            {
                                EnumSchema(objectConstruct00, xmlSchemaSequence.Items);
                            }
                        }
                    }
                }
            }
        }
 static void CheckObjects(ConformanceCheckContext ctx, ConformanceChecker checker, Hashtable visitedObjects, XmlSchemaObjectCollection col)
 {
     foreach (XmlSchemaObject item in col)
     {
         Check(ctx, checker, visitedObjects, item);
     }
 }
        private void ExportMembersMapSchema(XmlSchema schema, ClassMap map, XmlTypeMapping baseMap, XmlSchemaObjectCollection outAttributes, out XmlSchemaSequence particle, out XmlSchemaAnyAttribute anyAttribute)
        {
            particle = null;
            XmlSchemaSequence xmlSchemaSequence = new XmlSchemaSequence();
            ICollection       elementMembers    = map.ElementMembers;

            if (elementMembers != null && !map.HasSimpleContent)
            {
                foreach (object obj in elementMembers)
                {
                    XmlTypeMapMemberElement xmlTypeMapMemberElement = (XmlTypeMapMemberElement)obj;
                    if (baseMap == null || !this.DefinedInBaseMap(baseMap, xmlTypeMapMemberElement))
                    {
                        Type type = xmlTypeMapMemberElement.GetType();
                        if (type == typeof(XmlTypeMapMemberFlatList))
                        {
                            XmlSchemaParticle schemaArrayElement = this.GetSchemaArrayElement(schema, xmlTypeMapMemberElement.ElementInfo);
                            if (schemaArrayElement != null)
                            {
                                xmlSchemaSequence.Items.Add(schemaArrayElement);
                            }
                        }
                        else if (type == typeof(XmlTypeMapMemberAnyElement))
                        {
                            xmlSchemaSequence.Items.Add(this.GetSchemaArrayElement(schema, xmlTypeMapMemberElement.ElementInfo));
                        }
                        else if (type == typeof(XmlTypeMapMemberElement))
                        {
                            this.GetSchemaElement(schema, (XmlTypeMapElementInfo)xmlTypeMapMemberElement.ElementInfo[0], xmlTypeMapMemberElement.DefaultValue, true, new XmlSchemaExporter.XmlSchemaObjectContainer(xmlSchemaSequence));
                        }
                        else
                        {
                            this.GetSchemaElement(schema, (XmlTypeMapElementInfo)xmlTypeMapMemberElement.ElementInfo[0], true, new XmlSchemaExporter.XmlSchemaObjectContainer(xmlSchemaSequence));
                        }
                    }
                }
            }
            if (xmlSchemaSequence.Items.Count > 0)
            {
                particle = xmlSchemaSequence;
            }
            ICollection attributeMembers = map.AttributeMembers;

            if (attributeMembers != null)
            {
                foreach (object obj2 in attributeMembers)
                {
                    XmlTypeMapMemberAttribute xmlTypeMapMemberAttribute = (XmlTypeMapMemberAttribute)obj2;
                    if (baseMap == null || !this.DefinedInBaseMap(baseMap, xmlTypeMapMemberAttribute))
                    {
                        outAttributes.Add(this.GetSchemaAttribute(schema, xmlTypeMapMemberAttribute, true));
                    }
                }
            }
            XmlTypeMapMember defaultAnyAttributeMember = map.DefaultAnyAttributeMember;

            if (defaultAnyAttributeMember != null)
            {
                anyAttribute = new XmlSchemaAnyAttribute();
            }
            else
            {
                anyAttribute = null;
            }
        }
Example #20
0
        public static void WriteConstraintTable(this MamlWriter writer, Context context, XmlSchemaObjectCollection constraints)
        {
            if (constraints.Count == 0)
            {
                return;
            }

            writer.StartTable();
            writer.StartTableHeader();
            writer.StartTableRow();

            writer.WriteRowEntry(String.Empty);

            writer.WriteRowEntry("Type");

            writer.WriteRowEntry("Description");

            writer.WriteRowEntry("Selector");

            writer.WriteRowEntry("Fields");

            writer.EndTableRow();
            writer.EndTableHeader();

            var rowBuilder = new ConstraintRowWriter(writer, context);

            rowBuilder.Traverse(constraints);

            writer.EndTable();
        }
Example #21
0
 public SUPXsdAttributes(XmlSchemaObjectCollection xsdAttributes)
 {
     this.xsdAttributes = xsdAttributes;
 }
Example #22
0
        public static void WriteConstraintsSection(this MamlWriter writer, Context context, XmlSchemaObjectCollection constraints)
        {
            if (!context.Configuration.DocumentConstraints)
            {
                return;
            }

            writer.StartSection("Constraints", "constraints");
            writer.WriteConstraintTable(context, constraints);
            writer.EndSection();
        }
Example #23
0
        private static SegmentErrorContext ResolveUnexpected(XElement failedElement, XmlSchemaSet schemas, ErrorCodes errorCode)
        {
            foreach (XmlSchema schema in schemas.Schemas())
            {
                foreach (XmlSchemaElement element in schema.Elements.Values)
                {
                    if (element.QualifiedName.Name == failedElement.Name.LocalName)
                    {
                        var complexType = element.ElementSchemaType as XmlSchemaComplexType;

                        if (complexType != null)
                        {
                            XmlSchemaObjectCollection items = null;
                            var sequence = complexType.ContentTypeParticle as XmlSchemaSequence;
                            if (sequence != null)
                            {
                                items = sequence.Items;
                            }

                            if (sequence == null)
                            {
                                var all = complexType.ContentTypeParticle as XmlSchemaAll;
                                if (all != null)
                                {
                                    items = all.Items;
                                }
                            }

                            if (items == null)
                            {
                                continue;
                            }

                            foreach (var item in items)
                            {
                                var childElement = (XmlSchemaElement)item;
                                var match        = failedElement.Elements()
                                                   .Where(e => e.Name.LocalName == childElement.QualifiedName.Name).ToList();

                                if ((!match.Any() && Decimal.ToInt32(childElement.MinOccurs) == 1) ||
                                    (match.Any() && Decimal.ToInt32(childElement.MaxOccurs) < match.Count))
                                {
                                    if (childElement.QualifiedName.Name.StartsWith("S_", StringComparison.Ordinal))
                                    {
                                        return(BuildSegmentContext(childElement.QualifiedName.Name,
                                                                   failedElement, errorCode));
                                    }

                                    if (childElement.QualifiedName.Name.StartsWith("C_", StringComparison.Ordinal))
                                    {
                                        return(BuildCompositeDataElementContext(childElement.QualifiedName.Name,
                                                                                failedElement, errorCode));
                                    }

                                    if (childElement.QualifiedName.Name.StartsWith("D_", StringComparison.Ordinal))
                                    {
                                        return(BuildDataElementContext(childElement.QualifiedName.Name,
                                                                       failedElement, null, errorCode));
                                    }

                                    return(BuildOtherContext(childElement, failedElement, errorCode));
                                }
                            }
                        }
                    }
                }
            }

            return(null);
        }
Example #24
0
            public void InitializeChildren(SchemaObject theObject, XmlSchemaObject xmlObject)
            {
                XmlSchemaComplexType complexType = xmlObject as XmlSchemaComplexType;

                if (complexType == null && xmlObject is XmlSchemaElement)
                {
                    complexType = ((XmlSchemaElement)xmlObject).ElementSchemaType as XmlSchemaComplexType;
                }

                // if we don't have a complex type, we don't have any children to work with
                if (complexType == null)
                {
                    theObject.IsInitialized = true;
                    return;
                }

                XmlSchemaComplexType baseComplexType = complexType.BaseXmlSchemaType as XmlSchemaComplexType;

                // Load the base type info
                if (baseComplexType != null)
                {
                    InitializeChildren(theObject, baseComplexType);
                }

                theObject.IsInitialized = true;

                XmlSchemaObjectCollection attributes          = complexType.Attributes;
                XmlSchemaSequence         complexTypeSequence = complexType.ContentTypeParticle as XmlSchemaSequence;
                XmlSchemaChoice           complexTypeChoice   = complexType.ContentTypeParticle as XmlSchemaChoice;

                // Add attributes
                XmlSchemaComplexContentRestriction restriction    = complexType.ContentModel != null ? complexType.ContentModel.Content as XmlSchemaComplexContentRestriction : null;
                XmlSchemaComplexContentExtension   extension      = complexType.ContentModel != null ? complexType.ContentModel.Content as XmlSchemaComplexContentExtension : null;
                XmlSchemaObjectCollection          baseAttributes = null;

                if (restriction != null)
                {
                    baseAttributes = restriction.Attributes;
                }
                else if (extension != null)
                {
                    baseAttributes = extension.Attributes;
                }

                if (baseAttributes != null)
                {
                    foreach (XmlSchemaObject cObject in baseAttributes)
                    {
                        XmlSchemaAttribute cAttribute = cObject as XmlSchemaAttribute;

                        // TODO: Do something more complicated when cObject is an attribute group reference
                        if (cAttribute == null)
                        {
                            continue;
                        }

                        var foundChild = theObject.Children.SingleOrDefault(y => y.Name == cAttribute.Name);
                        var newChild   = new SchemaObject(theObject.simpleSchema, cAttribute, theObject.IsChoice)
                        {
                            Parent = theObject,
                            Name   = this.SimpleSchema.GetName(cAttribute.QualifiedName, cAttribute.RefName),
                            Type   = ObjectTypes.Attribute
                        };

                        if (foundChild != null && restriction != null)
                        {
                            var foundIndex = theObject.Children.IndexOf(foundChild);
                            theObject.Children.RemoveAt(foundIndex);
                            theObject.Children.Insert(foundIndex, newChild);
                        }
                        else if (foundChild == null)
                        {
                            theObject.Children.Add(newChild);
                        }
                    }
                }

                foreach (XmlSchemaObject cObject in complexType.Attributes)
                {
                    XmlSchemaAttribute cAttribute = cObject as XmlSchemaAttribute;

                    // TODO: More complicated logic to determine if a restriction is being applied
                    if (cAttribute != null && !theObject.Children.Exists(y => y.Name == cAttribute.Name))
                    {
                        theObject.Children.Add(
                            new SchemaObject(theObject.simpleSchema, cAttribute, theObject.IsChoice)
                        {
                            Parent = theObject,
                            Name   = this.SimpleSchema.GetName(cAttribute.QualifiedName, cAttribute.RefName),
                            Type   = ObjectTypes.Attribute
                        });
                    }
                }

                bool update = extension != null || restriction != null;

                // Add child elements (un-initialized)
                if (complexTypeSequence != null)
                {
                    InitializeXmlSequence(theObject, complexTypeSequence, update);
                }

                // Add all choice items
                if (complexTypeChoice != null)
                {
                    InitializeXmlChoice(theObject, complexTypeChoice, update);
                }
            }
 internal void Depends(XmlSchemaObject item, ArrayList refs)
 {
     if ((item != null) && (this.scope[item] == null))
     {
         Type c = item.GetType();
         if (typeof(XmlSchemaType).IsAssignableFrom(c))
         {
             XmlQualifiedName          empty      = XmlQualifiedName.Empty;
             XmlSchemaType             o          = null;
             XmlSchemaParticle         particle   = null;
             XmlSchemaObjectCollection attributes = null;
             if (item is XmlSchemaComplexType)
             {
                 XmlSchemaComplexType type3 = (XmlSchemaComplexType)item;
                 if (type3.ContentModel != null)
                 {
                     XmlSchemaContent content = type3.ContentModel.Content;
                     if (content is XmlSchemaComplexContentRestriction)
                     {
                         empty      = ((XmlSchemaComplexContentRestriction)content).BaseTypeName;
                         attributes = ((XmlSchemaComplexContentRestriction)content).Attributes;
                     }
                     else if (content is XmlSchemaSimpleContentRestriction)
                     {
                         XmlSchemaSimpleContentRestriction restriction = (XmlSchemaSimpleContentRestriction)content;
                         if (restriction.BaseType != null)
                         {
                             o = restriction.BaseType;
                         }
                         else
                         {
                             empty = restriction.BaseTypeName;
                         }
                         attributes = restriction.Attributes;
                     }
                     else if (content is XmlSchemaComplexContentExtension)
                     {
                         XmlSchemaComplexContentExtension extension = (XmlSchemaComplexContentExtension)content;
                         attributes = extension.Attributes;
                         particle   = extension.Particle;
                         empty      = extension.BaseTypeName;
                     }
                     else if (content is XmlSchemaSimpleContentExtension)
                     {
                         XmlSchemaSimpleContentExtension extension2 = (XmlSchemaSimpleContentExtension)content;
                         attributes = extension2.Attributes;
                         empty      = extension2.BaseTypeName;
                     }
                 }
                 else
                 {
                     attributes = type3.Attributes;
                     particle   = type3.Particle;
                 }
                 if (particle is XmlSchemaGroupRef)
                 {
                     XmlSchemaGroupRef ref2 = (XmlSchemaGroupRef)particle;
                     particle = ((XmlSchemaGroup)this.schemas.Find(ref2.RefName, typeof(XmlSchemaGroup), false)).Particle;
                 }
                 else if (particle is XmlSchemaGroupBase)
                 {
                     particle = (XmlSchemaGroupBase)particle;
                 }
             }
             else if (item is XmlSchemaSimpleType)
             {
                 XmlSchemaSimpleType        type4    = (XmlSchemaSimpleType)item;
                 XmlSchemaSimpleTypeContent content2 = type4.Content;
                 if (content2 is XmlSchemaSimpleTypeRestriction)
                 {
                     o     = ((XmlSchemaSimpleTypeRestriction)content2).BaseType;
                     empty = ((XmlSchemaSimpleTypeRestriction)content2).BaseTypeName;
                 }
                 else if (content2 is XmlSchemaSimpleTypeList)
                 {
                     XmlSchemaSimpleTypeList list = (XmlSchemaSimpleTypeList)content2;
                     if ((list.ItemTypeName != null) && !list.ItemTypeName.IsEmpty)
                     {
                         empty = list.ItemTypeName;
                     }
                     if (list.ItemType != null)
                     {
                         o = list.ItemType;
                     }
                 }
                 else if (content2 is XmlSchemaSimpleTypeRestriction)
                 {
                     empty = ((XmlSchemaSimpleTypeRestriction)content2).BaseTypeName;
                 }
                 else if (c == typeof(XmlSchemaSimpleTypeUnion))
                 {
                     XmlQualifiedName[] memberTypes = ((XmlSchemaSimpleTypeUnion)item).MemberTypes;
                     if (memberTypes != null)
                     {
                         for (int i = 0; i < memberTypes.Length; i++)
                         {
                             XmlSchemaType type5 = (XmlSchemaType)this.schemas.Find(memberTypes[i], typeof(XmlSchemaType), false);
                             this.AddRef(refs, type5);
                         }
                     }
                 }
             }
             if (((o == null) && !empty.IsEmpty) && (empty.Namespace != "http://www.w3.org/2001/XMLSchema"))
             {
                 o = (XmlSchemaType)this.schemas.Find(empty, typeof(XmlSchemaType), false);
             }
             if (o != null)
             {
                 this.AddRef(refs, o);
             }
             if (particle != null)
             {
                 this.Depends(particle, refs);
             }
             if (attributes != null)
             {
                 for (int j = 0; j < attributes.Count; j++)
                 {
                     this.Depends(attributes[j], refs);
                 }
             }
         }
         else if (c == typeof(XmlSchemaElement))
         {
             XmlSchemaElement element = (XmlSchemaElement)item;
             if (!element.SubstitutionGroup.IsEmpty && (element.SubstitutionGroup.Namespace != "http://www.w3.org/2001/XMLSchema"))
             {
                 XmlSchemaElement element2 = (XmlSchemaElement)this.schemas.Find(element.SubstitutionGroup, typeof(XmlSchemaElement), false);
                 this.AddRef(refs, element2);
             }
             if (!element.RefName.IsEmpty)
             {
                 element = (XmlSchemaElement)this.schemas.Find(element.RefName, typeof(XmlSchemaElement), false);
                 this.AddRef(refs, element);
             }
             else if (!element.SchemaTypeName.IsEmpty)
             {
                 XmlSchemaType type6 = (XmlSchemaType)this.schemas.Find(element.SchemaTypeName, typeof(XmlSchemaType), false);
                 this.AddRef(refs, type6);
             }
             else
             {
                 this.Depends(element.SchemaType, refs);
             }
         }
         else if (c == typeof(XmlSchemaGroup))
         {
             this.Depends(((XmlSchemaGroup)item).Particle);
         }
         else if (c == typeof(XmlSchemaGroupRef))
         {
             XmlSchemaGroup group = (XmlSchemaGroup)this.schemas.Find(((XmlSchemaGroupRef)item).RefName, typeof(XmlSchemaGroup), false);
             this.AddRef(refs, group);
         }
         else if (typeof(XmlSchemaGroupBase).IsAssignableFrom(c))
         {
             foreach (XmlSchemaObject obj2 in ((XmlSchemaGroupBase)item).Items)
             {
                 this.Depends(obj2, refs);
             }
         }
         else if (c == typeof(XmlSchemaAttributeGroupRef))
         {
             XmlSchemaAttributeGroup group2 = (XmlSchemaAttributeGroup)this.schemas.Find(((XmlSchemaAttributeGroupRef)item).RefName, typeof(XmlSchemaAttributeGroup), false);
             this.AddRef(refs, group2);
         }
         else if (c == typeof(XmlSchemaAttributeGroup))
         {
             foreach (XmlSchemaObject obj3 in ((XmlSchemaAttributeGroup)item).Attributes)
             {
                 this.Depends(obj3, refs);
             }
         }
         else if (c == typeof(XmlSchemaAttribute))
         {
             XmlSchemaAttribute attribute = (XmlSchemaAttribute)item;
             if (!attribute.RefName.IsEmpty)
             {
                 attribute = (XmlSchemaAttribute)this.schemas.Find(attribute.RefName, typeof(XmlSchemaAttribute), false);
                 this.AddRef(refs, attribute);
             }
             else if (!attribute.SchemaTypeName.IsEmpty)
             {
                 XmlSchemaType type7 = (XmlSchemaType)this.schemas.Find(attribute.SchemaTypeName, typeof(XmlSchemaType), false);
                 this.AddRef(refs, type7);
             }
             else
             {
                 this.Depends(attribute.SchemaType, refs);
             }
         }
         if (typeof(XmlSchemaAnnotated).IsAssignableFrom(c))
         {
             XmlAttribute[] unhandledAttributes = ((XmlSchemaAnnotated)item).UnhandledAttributes;
             if (unhandledAttributes != null)
             {
                 for (int k = 0; k < unhandledAttributes.Length; k++)
                 {
                     XmlAttribute attribute2 = unhandledAttributes[k];
                     if ((attribute2.LocalName == "arrayType") && (attribute2.NamespaceURI == "http://schemas.xmlsoap.org/wsdl/"))
                     {
                         string           str;
                         XmlQualifiedName name  = TypeScope.ParseWsdlArrayType(attribute2.Value, out str, item);
                         XmlSchemaType    type8 = (XmlSchemaType)this.schemas.Find(name, typeof(XmlSchemaType), false);
                         this.AddRef(refs, type8);
                     }
                 }
             }
         }
     }
 }
Example #26
0
        protected override void Seed(CAFE.DAL.DbContexts.ApplicationDbContext context)
        {
            //  This method will be called after migrating to the latest version.

            try
            {
                var permanentUserName = WebConfigurationManager.AppSettings["PermanentUserName"];
                var users             = new List <DbUser>
                {
                    new DbUser()
                    {
                        Id                   = Guid.Parse("2218929f-988c-e611-9c39-f0761cf9a82c"),
                        Email                = "*****@*****.**",
                        Name                 = "Administrator",
                        Surname              = "First",
                        UserName             = "******",
                        PostalAddress        = "38 avenue de l'Opera, F-75002 Paris, France",
                        PhoneNumber          = "+380951234567",
                        PasswordHash         = "AL39j/DOuiN+wzEQya/wDhPIkg9ljb3wak1Zco3YaQMsEcRYvwxjN5GWsgiLnfMtvg==", //111111
                        SecurityStamp        = "6ddca9e3-73d9-43b1-be6c-ed6c2fe6d4a2",
                        AcceptanceDate       = new System.DateTime(2010, 10, 10, 10, 10, 10),
                        AccessFailedCount    = 0,
                        LockoutEndDateUtc    = null,
                        PhoneNumberConfirmed = true,
                        TwoFactorEnabled     = false,
                        LockoutEnabled       = false,
                        IsActive             = true,
                        IsAccepted           = true,
                        EmailConfirmed       = true
                    },
                    new DbUser()
                    {
                        Id                   = Guid.Parse("B4ADCD73-F17F-4F8D-833A-CD546702654A"),
                        Email                = "*****@*****.**",
                        Name                 = "User",
                        Surname              = "First",
                        UserName             = "******",
                        PostalAddress        = "Unit 42, Land of Bargains Shopping Paradise, 12 Highway 101, Boston, MA, USA",
                        PhoneNumber          = "+130591234567",
                        PasswordHash         = "AL39j/DOuiN+wzEQya/wDhPIkg9ljb3wak1Zco3YaQMsEcRYvwxjN5GWsgiLnfMtvg==", //111111
                        SecurityStamp        = "6ddca9e3-73d9-43b1-be6c-ed6c2fe6d4a2",
                        AcceptanceDate       = new System.DateTime(2011, 1, 1, 1, 1, 1),
                        AccessFailedCount    = 0,
                        LockoutEndDateUtc    = null,
                        PhoneNumberConfirmed = true,
                        TwoFactorEnabled     = false,
                        LockoutEnabled       = false,
                        IsActive             = true,
                        IsAccepted           = true,
                        EmailConfirmed       = true,
                        Roles                = new List <DbRole> {
                        }
                    },
                    new DbUser()
                    {
                        Id                   = Guid.Parse("B10C1E4A-61A1-4B0D-A2C5-F3A2AF1483BF"),
                        Email                = permanentUserName + "@cafe.com",
                        Name                 = permanentUserName,
                        Surname              = "User",
                        UserName             = permanentUserName,
                        PostalAddress        = "When User decides to delete an account but keep the data, this data will be assigned to this account",
                        PhoneNumber          = "",
                        PasswordHash         = "AL39j/DOuiN+wzEQya/wDhPIkg9ljb3wak1Zco3YaQMsEcRYvwxjN5GWsgiLnfMtvg==", //111111
                        SecurityStamp        = "6ddca9e3-73d9-43b1-be6c-ed6c2fe6d4a2",
                        AcceptanceDate       = new System.DateTime(2016, 1, 1, 1, 1, 1),
                        AccessFailedCount    = 0,
                        LockoutEndDateUtc    = null,
                        PhoneNumberConfirmed = true,
                        TwoFactorEnabled     = false,
                        LockoutEnabled       = false,
                        IsActive             = true,
                        IsAccepted           = true,
                        EmailConfirmed       = true,
                        Roles                = new List <DbRole> {
                        }
                    }
                };

                var roles = new[]
                {
                    new DbRole()
                    {
                        Id            = Guid.Parse("2318929f-988c-e611-9c39-f0761cf9a82c"),
                        Name          = "Administrator",
                        Discriminator = "Administrator's role",
                        IsGroup       = false,
                        Users         = new [] { users[0] }
                    },
                    new DbRole()
                    {
                        Id            = Guid.Parse("58307169-A9A7-4D48-B2C2-E86A466B911D"),
                        Name          = "Curator",
                        Discriminator = "Curator's role",
                        IsGroup       = false
                    },
                    new DbRole()
                    {
                        Id            = Guid.Parse("81C6630F-ADE9-45F5-A3CE-029D0FEF9FC8"),
                        Name          = "User",
                        Discriminator = "User's role",
                        IsGroup       = false,
                        Users         = new [] { users[1], users[2] }
                    }
                };

                foreach (var role in roles)
                {
                    context.Roles.AddOrUpdate(x => x.Id, role);
                }

                foreach (var user in users)
                {
                    context.Users.AddOrUpdate(x => x.Id, user);
                }

                /*
                 * var userFiles = new[]
                 * {
                 *  new DbUserFile
                 *  {
                 *     Id = Guid.Parse("af3b0a4f-fd2a-45dc-b4c2-444289636332"),
                 *     Name = "test-file.txt",
                 *     CreationDate = System.DateTime.Parse("2016-10-27 17:39:25.900"),
                 *     AcceptedGroups = new List<DbRole> { },
                 *     AcceptedUsers = new List<DbUser> { users[1] },
                 *     AccessMode = DbUserFile.DbFileAccessMode.Explicit,
                 *     Type = DbUserFile.DbFileType.Other,
                 *     Description = "This is text file",
                 *     Owner = users[0]
                 *  },
                 *  new DbUserFile
                 *  {
                 *     Id = Guid.Parse("fa3f9e9f-ced2-4653-8de1-a960945e4a79"),
                 *     Name = "test-file.mp3",
                 *     CreationDate = System.DateTime.Parse("2016-10-27 18:12:27.153"),
                 *     AcceptedGroups = new List<DbRole> { },
                 *     AcceptedUsers = new List<DbUser> { },
                 *     AccessMode = DbUserFile.DbFileAccessMode.Explicit,
                 *     Type = DbUserFile.DbFileType.Audio,
                 *     Description = "This is audio file",
                 *     Owner = users[0]
                 *  }
                 * };
                 *
                 * foreach (var userFile in userFiles)
                 *  context.UserFiles.AddOrUpdate(x => x.Id, userFiles);
                 *
                 * var accessibleResources = new[]
                 * {
                 *  new DbAccessibleResource
                 *  {
                 *     Id = 1,
                 *     Kind = 0,
                 *     Owner = users[0],
                 *     ResourceId = Guid.Parse("af3b0a4f-fd2a-45dc-b4c2-444289636332")
                 *  },
                 *  new DbAccessibleResource
                 *  {
                 *     Id = 2,
                 *     Kind = 0,
                 *     Owner = users[0],
                 *     ResourceId = Guid.Parse("fa3f9e9f-ced2-4653-8de1-a960945e4a79")
                 *  }
                 * };
                 *
                 * var accessRequests = new[]
                 * {
                 *  new DbAccessRequest
                 *  {
                 *      Id = 1,
                 *      CreationDate = System.DateTime.Parse("2016-10-31 23:15:26.810"),
                 *      RequestSubject = "Access request 1",
                 *      RequestMessage = "Gime me access, please",
                 *      RequestedResources = new List<DbAccessibleResource> { accessibleResources[0] }
                 *  },
                 *  new DbAccessRequest
                 *  {
                 *      Id = 2,
                 *      CreationDate = System.DateTime.Parse("2016-10-31 23:16:07.120"),
                 *      RequestSubject = "Access request 2",
                 *      RequestMessage = "I need to access to this mp3 file!",
                 *      RequestedResources = new List<DbAccessibleResource> { accessibleResources[1] },
                 *  }
                 * };
                 *
                 *
                 * var conversations = new[]
                 * {
                 *  new DbConversation
                 *  {
                 *      Id = 1,
                 *      HasRecieverUnreadMessages = false,
                 *      Receiver = users[0],
                 *      Request = accessRequests[0],
                 *      Requester = users[1],
                 *      Status = DbAccessRequestStatus.Open
                 *  },
                 *  new DbConversation
                 *  {
                 *      Id = 2,
                 *      HasRecieverUnreadMessages = true,
                 *      Receiver = users[0],
                 *      Request = accessRequests[1],
                 *      Requester = users[1],
                 *      Status = DbAccessRequestStatus.Accepted
                 *  }
                 * };
                 *
                 * var messages = new[]
                 * {
                 *  new DbMessage
                 *  {
                 *      Id = 1,
                 *      Conversation = conversations[0],
                 *      Text = "Gime me access, please.",
                 *      CreationDate = System.DateTime.Parse("2016-10-31 23:15:27.137"),
                 *      Receiver = users[0],
                 *      Sender = users[1]
                 *  },
                 *  new DbMessage
                 *  {
                 *      Id = 2,
                 *      Conversation = conversations[1],
                 *      Text = "I need to access to this mp3 file!",
                 *      CreationDate = System.DateTime.Parse("2016-10-31 23:16:07.137"),
                 *      Receiver = users[0],
                 *      Sender = users[1]
                 *  },
                 *  new DbMessage
                 *  {
                 *      Id = 3,
                 *      Conversation = conversations[0],
                 *      Text = "Ok, I will give you access. Enjoy it!!",
                 *      CreationDate = System.DateTime.Parse("2016-10-31 23:24:52.193"),
                 *      Receiver = users[1],
                 *      Sender = users[0]
                 *  }
                 * };
                 *
                 *
                 * foreach (var role in roles)
                 *  context.Roles.AddOrUpdate(x => x.Id, role);
                 *
                 * foreach (var user in users)
                 *  context.Users.AddOrUpdate(x => x.Id, user);
                 *
                 * foreach (var accessibleResource in accessibleResources)
                 *  context.AccessibleResources.AddOrUpdate(x => x.Id, accessibleResource);
                 *
                 * foreach (var userFile in userFiles)
                 *  context.UserFiles.AddOrUpdate(x => x.Id, userFiles);
                 *
                 * foreach (var accessRequest in accessRequests)
                 *  context.AccessRequests.AddOrUpdate(x => x.Id, accessRequest);
                 *
                 * foreach (var conversation in conversations)
                 *  context.Conversations.AddOrUpdate(x => x.Id, conversation);
                 *
                 * foreach (var message in messages)
                 *  context.Messages.AddOrUpdate(x => x.Id, message);
                 */

                ////////Seed for vocabularies

                var directory = AppDomain.CurrentDomain.BaseDirectory;
                //For Denis =>
                //string schemaPath = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory).Parent.Parent.Parent.FullName + "\\Tools\\ModelGenerator\\Compiled\\ease.xsd";
                var           baseBath         = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory).FullName;
                string        schemaPath       = baseBath + "\\ease.xsd";
                XmlTextReader reader           = new XmlTextReader(schemaPath);
                XmlSchema     myschema         = XmlSchema.Read(reader, ValidationCallback);
                var           vocabularyValues = new List <DbVocabularyValue>();

                //First check that vocabulary values doesn't exists
                if (!context.VocabularyValues.Any())
                {
                    //Getting asm when stores vocabulary enums
                    var asm =
                        AppDomain.CurrentDomain.GetAssemblies()
                        .AsEnumerable()
                        .Where(w => w.FullName.Contains("CAFE.Core"))
                        .FirstOrDefault();

                    //Get enum types that is Enum, public and it's name ends with 'Vocabulary'
                    var enumTypes = asm.GetTypes()
                                    .Where(t => t.IsEnum && t.IsPublic && t.Name.ToLower().EndsWith("vocabulary"));

                    var enumDics = new Dictionary <string, List <string> >();

                    //Enumerate through each enum types and getting name or alias(XmlEnumAttribute)
                    foreach (var enumType in enumTypes)
                    {
                        var enumNames  = new List <string>();
                        var enemValues = Enum.GetNames(enumType).AsEnumerable();
                        foreach (var enemValue in enemValues)
                        {
                            var findedAlias = enemValue;
                            var memInfo     = enumType.GetMember(enemValue);
                            var attributes  = memInfo[0].GetCustomAttributes(typeof(XmlEnumAttribute),
                                                                             false);
                            if (attributes.Length > 0)
                            {
                                findedAlias = ((XmlEnumAttribute)attributes[0]).Name;
                            }

                            enumNames.Add(findedAlias);
                        }

                        enumDics.Add(enumType.Name, enumNames);
                    }

                    //Store finded vocabulary values into db with enum type
                    foreach (var enumDic in enumDics)
                    {
                        //Trace.WriteLine(enumDic.Key);

                        var simpleTypeItems = new XmlSchemaObjectCollection();
                        foreach (object item in myschema.Items)
                        {
                            if (item is XmlSchemaSimpleType)
                            {
                                var simpleType = item as XmlSchemaSimpleType;

                                //Trace.WriteLine(simpleType.Name);

                                if (simpleType.Name == enumDic.Key)
                                {
                                    var restrictionType = simpleType.Content as XmlSchemaSimpleTypeRestriction;
                                    if (restrictionType != null)
                                    {
                                        simpleTypeItems = restrictionType.Facets;
                                    }
                                    var compositeType = simpleType.Content as XmlSchemaSimpleTypeUnion;
                                    if (compositeType != null)
                                    {
                                        if (compositeType.MemberTypes.Any())
                                        {
                                            var firstFacetsType = compositeType.MemberTypes.First();
                                            if (firstFacetsType != null)
                                            {
                                                var foundType = FindTypeByName(firstFacetsType.Name, myschema.Items);
                                                if (foundType != null)
                                                {
                                                    var firstRestrictionType = foundType.Content as XmlSchemaSimpleTypeRestriction;
                                                    if (firstRestrictionType != null)
                                                    {
                                                        simpleTypeItems = firstRestrictionType.Facets;
                                                    }
                                                }
                                            }
                                        }
                                    }
                                    break;
                                }
                            }
                        }

                        foreach (var enVal in enumDic.Value)
                        {
                            //Trace.WriteLine(enVal);

                            var documentation = new XmlSchemaDocumentation();
                            foreach (var item in simpleTypeItems)
                            {
                                if (!(item is XmlSchemaEnumerationFacet))
                                {
                                    continue;
                                }

                                var name = (item as XmlSchemaEnumerationFacet).Value;

                                if (name != enVal)
                                {
                                    continue;
                                }

                                var items = (item as XmlSchemaEnumerationFacet).Annotation?.Items;
                                if (null == items)
                                {
                                    continue;
                                }

                                var itemfound = false;
                                foreach (var facetItem in items)
                                {
                                    if (facetItem is XmlSchemaDocumentation)
                                    {
                                        documentation = facetItem as XmlSchemaDocumentation;
                                        itemfound     = true;
                                        break;
                                    }
                                }
                                if (itemfound)
                                {
                                    break;
                                }
                            }

                            vocabularyValues.Add(new DbVocabularyValue()
                            {
                                Type        = enumDic.Key,
                                Value       = enVal,
                                Description = documentation?.Markup?[0].InnerText
                            });
                        }
                    }
                }

                if (!context.SchemaItemDescriptions.Any())
                {
                    var items = LoadXsdDescriptions(schemaPath);
                    WriteSchemaDataToDatabase(items, context);
                }

                //Adding descriptions for labels
                System.Xml.Linq.XDocument doc = System.Xml.Linq.XDocument.Load(schemaPath);
                var elements2 = doc.Descendants().Where(d => d.Name.LocalName == "documentation");

                foreach (var item in elements2)
                {
                    var name = item.Parent.Parent.FirstAttribute.Value;
                    if (null == vocabularyValues.FirstOrDefault(v => v.Type == name))
                    {
                        vocabularyValues.Add(new DbVocabularyValue()
                        {
                            Type        = name,
                            Value       = "-1",
                            Description = item.Value
                        });
                    }
                }

                context.VocabularyValues.AddRange(vocabularyValues);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        // ReSharper disable once FunctionComplexityOverflow
        private TypeModel CreateTypeModel(Uri source, XmlSchemaAnnotated type, XmlQualifiedName qualifiedName)
        {
            TypeModel typeModel;

            if (!qualifiedName.IsEmpty && Types.TryGetValue(qualifiedName, out typeModel))
            {
                return(typeModel);
            }

            if (source == null)
            {
                throw new ArgumentNullException("source");
            }
            var namespaceModel = CreateNamespaceModel(source, qualifiedName);

            var docs = GetDocumentation(type);

            var group = type as XmlSchemaGroup;

            if (group != null)
            {
                var name = "I" + ToTitleCase(qualifiedName.Name);
                if (namespaceModel != null)
                {
                    name = namespaceModel.GetUniqueTypeName(name);
                }

                var interfaceModel = new InterfaceModel(_configuration)
                {
                    Name          = name,
                    Namespace     = namespaceModel,
                    XmlSchemaName = qualifiedName
                };

                interfaceModel.Documentation.AddRange(docs);

                if (namespaceModel != null)
                {
                    namespaceModel.Types[name] = interfaceModel;
                }
                if (!qualifiedName.IsEmpty)
                {
                    Types[qualifiedName] = interfaceModel;
                }

                var particle   = group.Particle;
                var items      = GetElements(particle);
                var properties = CreatePropertiesForElements(source, interfaceModel, particle, items.Where(i => !(i.XmlParticle is XmlSchemaGroupRef)));
                interfaceModel.Properties.AddRange(properties);
                var interfaces = items.Select(i => i.XmlParticle).OfType <XmlSchemaGroupRef>()
                                 .Select(i => (InterfaceModel)CreateTypeModel(new Uri(i.SourceUri), Groups[i.RefName], i.RefName));
                interfaceModel.Interfaces.AddRange(interfaces);

                return(interfaceModel);
            }

            var attributeGroup = type as XmlSchemaAttributeGroup;

            if (attributeGroup != null)
            {
                var name = "I" + ToTitleCase(qualifiedName.Name);
                if (namespaceModel != null)
                {
                    name = namespaceModel.GetUniqueTypeName(name);
                }

                var interfaceModel = new InterfaceModel(_configuration)
                {
                    Name          = name,
                    Namespace     = namespaceModel,
                    XmlSchemaName = qualifiedName
                };

                interfaceModel.Documentation.AddRange(docs);

                if (namespaceModel != null)
                {
                    namespaceModel.Types[name] = interfaceModel;
                }
                if (!qualifiedName.IsEmpty)
                {
                    Types[qualifiedName] = interfaceModel;
                }

                var items      = attributeGroup.Attributes;
                var properties = CreatePropertiesForAttributes(source, interfaceModel, items.OfType <XmlSchemaAttribute>());
                interfaceModel.Properties.AddRange(properties);
                var interfaces = items.OfType <XmlSchemaAttributeGroupRef>()
                                 .Select(a => (InterfaceModel)CreateTypeModel(new Uri(a.SourceUri), AttributeGroups[a.RefName], a.RefName));
                interfaceModel.Interfaces.AddRange(interfaces);

                return(interfaceModel);
            }

            var complexType = type as XmlSchemaComplexType;

            if (complexType != null)
            {
                var name = ToTitleCase(qualifiedName.Name);
                if (namespaceModel != null)
                {
                    name = namespaceModel.GetUniqueTypeName(name);
                }

                var classModel = new ClassModel(_configuration)
                {
                    Name              = name,
                    Namespace         = namespaceModel,
                    XmlSchemaName     = qualifiedName,
                    XmlSchemaType     = complexType,
                    IsAbstract        = complexType.IsAbstract,
                    IsAnonymous       = complexType.QualifiedName.Name == "",
                    IsMixed           = complexType.IsMixed,
                    IsSubstitution    = complexType.Parent is XmlSchemaElement && !((XmlSchemaElement)complexType.Parent).SubstitutionGroup.IsEmpty,
                    EnableDataBinding = EnableDataBinding,
                };

                classModel.Documentation.AddRange(docs);

                if (namespaceModel != null)
                {
                    namespaceModel.Types[classModel.Name] = classModel;
                }

                if (!qualifiedName.IsEmpty)
                {
                    Types[qualifiedName] = classModel;
                }

                if (complexType.BaseXmlSchemaType != null && complexType.BaseXmlSchemaType.QualifiedName != AnyType)
                {
                    var baseModel = CreateTypeModel(source, complexType.BaseXmlSchemaType, complexType.BaseXmlSchemaType.QualifiedName);
                    classModel.BaseClass = baseModel;
                    if (baseModel is ClassModel)
                    {
                        ((ClassModel)classModel.BaseClass).DerivedTypes.Add(classModel);
                    }
                }

                XmlSchemaParticle particle = null;
                if (classModel.BaseClass != null)
                {
                    if (complexType.ContentModel.Content is XmlSchemaComplexContentExtension)
                    {
                        particle = ((XmlSchemaComplexContentExtension)complexType.ContentModel.Content).Particle;
                    }

                    // If it's a restriction, do not duplicate elements on the derived class, they're already in the base class.
                    // See https://msdn.microsoft.com/en-us/library/f3z3wh0y.aspx
                    //else if (complexType.ContentModel.Content is XmlSchemaComplexContentRestriction)
                    //    particle = ((XmlSchemaComplexContentRestriction)complexType.ContentModel.Content).Particle;
                }
                else
                {
                    particle = complexType.ContentTypeParticle;
                }

                var items      = GetElements(particle);
                var properties = CreatePropertiesForElements(source, classModel, particle, items);
                classModel.Properties.AddRange(properties);

                if (GenerateInterfaces)
                {
                    var interfaces = items.Select(i => i.XmlParticle).OfType <XmlSchemaGroupRef>()
                                     .Select(i => (InterfaceModel)CreateTypeModel(new Uri(i.SourceUri), Groups[i.RefName], i.RefName));
                    classModel.Interfaces.AddRange(interfaces);
                }

                XmlSchemaObjectCollection attributes = null;
                if (classModel.BaseClass != null)
                {
                    if (complexType.ContentModel.Content is XmlSchemaComplexContentExtension)
                    {
                        attributes = ((XmlSchemaComplexContentExtension)complexType.ContentModel.Content).Attributes;
                    }
                    else if (complexType.ContentModel.Content is XmlSchemaSimpleContentExtension)
                    {
                        attributes = ((XmlSchemaSimpleContentExtension)complexType.ContentModel.Content).Attributes;
                    }

                    // If it's a restriction, do not duplicate attributes on the derived class, they're already in the base class.
                    // See https://msdn.microsoft.com/en-us/library/f3z3wh0y.aspx
                    //else if (complexType.ContentModel.Content is XmlSchemaComplexContentRestriction)
                    //    attributes = ((XmlSchemaComplexContentRestriction)complexType.ContentModel.Content).Attributes;
                    //else if (complexType.ContentModel.Content is XmlSchemaSimpleContentRestriction)
                    //    attributes = ((XmlSchemaSimpleContentRestriction)complexType.ContentModel.Content).Attributes;
                }
                else
                {
                    attributes = complexType.Attributes;
                }

                if (attributes != null)
                {
                    var attributeProperties = CreatePropertiesForAttributes(source, classModel, attributes.Cast <XmlSchemaObject>());
                    classModel.Properties.AddRange(attributeProperties);

                    if (GenerateInterfaces)
                    {
                        var attributeInterfaces = attributes.OfType <XmlSchemaAttributeGroupRef>()
                                                  .Select(i => (InterfaceModel)CreateTypeModel(new Uri(i.SourceUri), AttributeGroups[i.RefName], i.RefName));
                        classModel.Interfaces.AddRange(attributeInterfaces);
                    }
                }

                if (complexType.AnyAttribute != null)
                {
                    var property = new PropertyModel(_configuration)
                    {
                        OwningType = classModel,
                        Name       = "AnyAttribute",
                        Type       = new SimpleModel(_configuration)
                        {
                            ValueType = typeof(XmlAttribute), UseDataTypeAttribute = false
                        },
                        IsAttribute  = true,
                        IsCollection = true,
                        IsAny        = true
                    };

                    var attributeDocs = GetDocumentation(complexType.AnyAttribute);
                    property.Documentation.AddRange(attributeDocs);

                    classModel.Properties.Add(property);
                }

                return(classModel);
            }

            var simpleType = type as XmlSchemaSimpleType;

            if (simpleType != null)
            {
                var restrictions = new List <RestrictionModel>();

                var typeRestriction = simpleType.Content as XmlSchemaSimpleTypeRestriction;
                if (typeRestriction != null)
                {
                    var enumFacets = typeRestriction.Facets.OfType <XmlSchemaEnumerationFacet>().ToList();
                    var isEnum     = (enumFacets.Count == typeRestriction.Facets.Count && enumFacets.Count != 0) ||
                                     (EnumTypes.Contains(typeRestriction.BaseTypeName.Name) && enumFacets.Any());
                    if (isEnum)
                    {
                        // we got an enum
                        var name = ToTitleCase(qualifiedName.Name);
                        if (namespaceModel != null)
                        {
                            name = namespaceModel.GetUniqueTypeName(name);
                        }

                        var enumModel = new EnumModel(_configuration)
                        {
                            Name          = name,
                            Namespace     = namespaceModel,
                            XmlSchemaName = qualifiedName,
                            XmlSchemaType = simpleType,
                        };

                        enumModel.Documentation.AddRange(docs);

                        foreach (var facet in enumFacets.DistinctBy(f => f.Value))
                        {
                            var value = new EnumValueModel
                            {
                                Name  = ToTitleCase(facet.Value).ToNormalizedEnumName(),
                                Value = facet.Value
                            };

                            var valueDocs = GetDocumentation(facet);
                            value.Documentation.AddRange(valueDocs);

                            var deprecated = facet.Annotation != null && facet.Annotation.Items.OfType <XmlSchemaAppInfo>()
                                             .Any(a => a.Markup.Any(m => m.Name == "annox:annotate" && m.HasChildNodes && m.FirstChild.Name == "jl:Deprecated"));
                            value.IsDeprecated = deprecated;

                            enumModel.Values.Add(value);
                        }

                        if (namespaceModel != null)
                        {
                            namespaceModel.Types[enumModel.Name] = enumModel;
                        }

                        if (!qualifiedName.IsEmpty)
                        {
                            Types[qualifiedName] = enumModel;
                        }

                        return(enumModel);
                    }

                    restrictions = GetRestrictions(typeRestriction.Facets.Cast <XmlSchemaFacet>(), simpleType).Where(r => r != null).Sanitize().ToList();
                }

                var simpleModelName = ToTitleCase(qualifiedName.Name);
                if (namespaceModel != null)
                {
                    simpleModelName = namespaceModel.GetUniqueTypeName(simpleModelName);
                }

                var simpleModel = new SimpleModel(_configuration)
                {
                    Name          = simpleModelName,
                    Namespace     = namespaceModel,
                    XmlSchemaName = qualifiedName,
                    XmlSchemaType = simpleType,
                    ValueType     = simpleType.Datatype.GetEffectiveType(_configuration),
                };

                simpleModel.Documentation.AddRange(docs);
                simpleModel.Restrictions.AddRange(restrictions);

                if (namespaceModel != null)
                {
                    namespaceModel.Types[simpleModel.Name] = simpleModel;
                }

                if (!qualifiedName.IsEmpty)
                {
                    Types[qualifiedName] = simpleModel;
                }

                return(simpleModel);
            }

            throw new Exception(string.Format("Cannot build declaration for {0}", qualifiedName));
        }
Example #28
0
        internal void Depends(XmlSchemaObject item, ArrayList refs)
        {
            if (item == null || _scope[item] != null)
            {
                return;
            }

            Type t = item.GetType();

            if (typeof(XmlSchemaType).IsAssignableFrom(t))
            {
                XmlQualifiedName          baseName   = XmlQualifiedName.Empty;
                XmlSchemaType             baseType   = null;
                XmlSchemaParticle         particle   = null;
                XmlSchemaObjectCollection attributes = null;

                if (item is XmlSchemaComplexType)
                {
                    XmlSchemaComplexType ct = (XmlSchemaComplexType)item;
                    if (ct.ContentModel != null)
                    {
                        XmlSchemaContent content = ct.ContentModel.Content;
                        if (content is XmlSchemaComplexContentRestriction)
                        {
                            baseName   = ((XmlSchemaComplexContentRestriction)content).BaseTypeName;
                            attributes = ((XmlSchemaComplexContentRestriction)content).Attributes;
                        }
                        else if (content is XmlSchemaSimpleContentRestriction)
                        {
                            XmlSchemaSimpleContentRestriction restriction = (XmlSchemaSimpleContentRestriction)content;
                            if (restriction.BaseType != null)
                            {
                                baseType = restriction.BaseType;
                            }
                            else
                            {
                                baseName = restriction.BaseTypeName;
                            }
                            attributes = restriction.Attributes;
                        }
                        else if (content is XmlSchemaComplexContentExtension)
                        {
                            XmlSchemaComplexContentExtension extension = (XmlSchemaComplexContentExtension)content;
                            attributes = extension.Attributes;
                            particle   = extension.Particle;
                            baseName   = extension.BaseTypeName;
                        }
                        else if (content is XmlSchemaSimpleContentExtension)
                        {
                            XmlSchemaSimpleContentExtension extension = (XmlSchemaSimpleContentExtension)content;
                            attributes = extension.Attributes;
                            baseName   = extension.BaseTypeName;
                        }
                    }
                    else
                    {
                        attributes = ct.Attributes;
                        particle   = ct.Particle;
                    }
                    if (particle is XmlSchemaGroupRef)
                    {
                        XmlSchemaGroupRef refGroup = (XmlSchemaGroupRef)particle;
                        particle = ((XmlSchemaGroup)_schemas.Find(refGroup.RefName, typeof(XmlSchemaGroup), false)).Particle;
                    }
                    else if (particle is XmlSchemaGroupBase)
                    {
                        particle = (XmlSchemaGroupBase)particle;
                    }
                }
                else if (item is XmlSchemaSimpleType)
                {
                    XmlSchemaSimpleType        simpleType = (XmlSchemaSimpleType)item;
                    XmlSchemaSimpleTypeContent content    = simpleType.Content;
                    if (content is XmlSchemaSimpleTypeRestriction)
                    {
                        baseType = ((XmlSchemaSimpleTypeRestriction)content).BaseType;
                        baseName = ((XmlSchemaSimpleTypeRestriction)content).BaseTypeName;
                    }
                    else if (content is XmlSchemaSimpleTypeList)
                    {
                        XmlSchemaSimpleTypeList list = (XmlSchemaSimpleTypeList)content;
                        if (list.ItemTypeName != null && !list.ItemTypeName.IsEmpty)
                        {
                            baseName = list.ItemTypeName;
                        }
                        if (list.ItemType != null)
                        {
                            baseType = list.ItemType;
                        }
                    }
                    else if (content is XmlSchemaSimpleTypeRestriction)
                    {
                        baseName = ((XmlSchemaSimpleTypeRestriction)content).BaseTypeName;
                    }
                    else if (t == typeof(XmlSchemaSimpleTypeUnion))
                    {
                        XmlQualifiedName[] memberTypes = ((XmlSchemaSimpleTypeUnion)item).MemberTypes;

                        if (memberTypes != null)
                        {
                            for (int i = 0; i < memberTypes.Length; i++)
                            {
                                XmlSchemaType type = (XmlSchemaType)_schemas.Find(memberTypes[i], typeof(XmlSchemaType), false);
                                AddRef(refs, type);
                            }
                        }
                    }
                }
                if (baseType == null && !baseName.IsEmpty && baseName.Namespace != XmlSchema.Namespace)
                {
                    baseType = (XmlSchemaType)_schemas.Find(baseName, typeof(XmlSchemaType), false);
                }

                if (baseType != null)
                {
                    AddRef(refs, baseType);
                }
                if (particle != null)
                {
                    Depends(particle, refs);
                }
                if (attributes != null)
                {
                    for (int i = 0; i < attributes.Count; i++)
                    {
                        Depends(attributes[i], refs);
                    }
                }
            }
            else if (t == typeof(XmlSchemaElement))
            {
                XmlSchemaElement el = (XmlSchemaElement)item;
                if (!el.SubstitutionGroup.IsEmpty)
                {
                    if (el.SubstitutionGroup.Namespace != XmlSchema.Namespace)
                    {
                        XmlSchemaElement head = (XmlSchemaElement)_schemas.Find(el.SubstitutionGroup, typeof(XmlSchemaElement), false);
                        AddRef(refs, head);
                    }
                }
                if (!el.RefName.IsEmpty)
                {
                    el = (XmlSchemaElement)_schemas.Find(el.RefName, typeof(XmlSchemaElement), false);
                    AddRef(refs, el);
                }
                else if (!el.SchemaTypeName.IsEmpty)
                {
                    XmlSchemaType type = (XmlSchemaType)_schemas.Find(el.SchemaTypeName, typeof(XmlSchemaType), false);
                    AddRef(refs, type);
                }
                else
                {
                    Depends(el.SchemaType, refs);
                }
            }
            else if (t == typeof(XmlSchemaGroup))
            {
                Depends(((XmlSchemaGroup)item).Particle);
            }
            else if (t == typeof(XmlSchemaGroupRef))
            {
                XmlSchemaGroup group = (XmlSchemaGroup)_schemas.Find(((XmlSchemaGroupRef)item).RefName, typeof(XmlSchemaGroup), false);
                AddRef(refs, group);
            }
            else if (typeof(XmlSchemaGroupBase).IsAssignableFrom(t))
            {
                foreach (XmlSchemaObject o in ((XmlSchemaGroupBase)item).Items)
                {
                    Depends(o, refs);
                }
            }
            else if (t == typeof(XmlSchemaAttributeGroupRef))
            {
                XmlSchemaAttributeGroup group = (XmlSchemaAttributeGroup)_schemas.Find(((XmlSchemaAttributeGroupRef)item).RefName, typeof(XmlSchemaAttributeGroup), false);
                AddRef(refs, group);
            }
            else if (t == typeof(XmlSchemaAttributeGroup))
            {
                foreach (XmlSchemaObject o in ((XmlSchemaAttributeGroup)item).Attributes)
                {
                    Depends(o, refs);
                }
            }
            else if (t == typeof(XmlSchemaAttribute))
            {
                XmlSchemaAttribute at = (XmlSchemaAttribute)item;
                if (!at.RefName.IsEmpty)
                {
                    at = (XmlSchemaAttribute)_schemas.Find(at.RefName, typeof(XmlSchemaAttribute), false);
                    AddRef(refs, at);
                }
                else if (!at.SchemaTypeName.IsEmpty)
                {
                    XmlSchemaType type = (XmlSchemaType)_schemas.Find(at.SchemaTypeName, typeof(XmlSchemaType), false);
                    AddRef(refs, type);
                }
                else
                {
                    Depends(at.SchemaType, refs);
                }
            }
            if (typeof(XmlSchemaAnnotated).IsAssignableFrom(t))
            {
                XmlAttribute[] attrs = (XmlAttribute[])((XmlSchemaAnnotated)item).UnhandledAttributes;

                if (attrs != null)
                {
                    for (int i = 0; i < attrs.Length; i++)
                    {
                        XmlAttribute attribute = attrs[i];
                        if (attribute.LocalName == Wsdl.ArrayType && attribute.NamespaceURI == Wsdl.Namespace)
                        {
                            string           dims;
                            XmlQualifiedName qname = TypeScope.ParseWsdlArrayType(attribute.Value, out dims, item);
                            XmlSchemaType    type  = (XmlSchemaType)_schemas.Find(qname, typeof(XmlSchemaType), false);
                            AddRef(refs, type);
                        }
                    }
                }
            }
        }
        private void handleObject(XmlSchemaObject o)
        {
            string str = "unknown";
            XmlSchemaObjectCollection children = new XmlSchemaObjectCollection();

            if (o is XmlSchema)
            {
                str      = "root";
                children = ((XmlSchema)o).Items;
            }
            else if (o is XmlSchemaComplexType)
            {
                XmlSchemaComplexType type = (XmlSchemaComplexType)o;
                startNewDbFile(type);
                str      = type.Name;
                children = type.Attributes;
                infos    = new List <TypeInfo> ();
            }
            else if (o is XmlSchemaAttribute)
            {
                XmlSchemaAttribute attribute = (XmlSchemaAttribute)o;
                addDbAttribute(attribute);
                str = string.Format("{0} ({1})", attribute.Name, attribute.AttributeSchemaType.TypeCode);
            }
            else if (o is XmlSchemaElement)
            {
                // children = ((XmlSchemaElement)o).
                XmlSchemaElement element = (XmlSchemaElement)o;
                foreach (XmlSchemaObject constraint in element.Constraints)
                {
                    if (constraint is XmlSchemaUnique)
                    {
                        XmlSchemaUnique unique = (XmlSchemaUnique)constraint;
                        List <string>   fields = new List <string> (unique.Fields.Count);
                        foreach (XmlSchemaObject field in unique.Fields)
                        {
                            if (field is XmlSchemaXPath)
                            {
                                fields.Add(((XmlSchemaXPath)field).XPath);
                            }
                        }
                        constraints.Add(new TableConstraint
                        {
                            Name   = unique.Name,
                            Table  = unique.Selector.XPath,
                            Fields = fields
                        });
                    }
                    else if (constraint is XmlSchemaKeyref)
                    {
                        XmlSchemaKeyref reference = (XmlSchemaKeyref)constraint;
                        string          fromTable = reference.Selector.XPath.Substring(3).Replace("_tables", "");
                        string          fromRow   = ((XmlSchemaXPath)reference.Fields [0]).XPath.Substring(1);
                        try {
                            TableReferenceEntry tableRef = resolveReference(reference.Name, fromTable, fromRow, reference.Refer.Name);
                            if (tableRef != null)
                            {
                                Console.WriteLine("{0}#{1} - {2}#{3}", tableRef.fromTable, tableRef.fromTableIndex, tableRef.toTable, tableRef.toTableIndex);
                            }
                            else
                            {
                                Console.WriteLine("could not resolve reference");
                            }
                        } catch (Exception x) {
                            Console.WriteLine(x);
                        }
                    }
                }
            }
            else
            {
                Console.WriteLine("unknown type: {0}", o);
            }

            if (o is XmlSchemaAnnotated && ((XmlSchemaAnnotated)o).UnhandledAttributes != null)
            {
                string attlist = "";
                new List <XmlAttribute> (((XmlSchemaAnnotated)o).UnhandledAttributes).ForEach(uh => attlist += " " + uh);
                str = string.Format("{0} (unhandled: {1})", str, attlist);
            }

            foreach (XmlSchemaObject child in children)
            {
                handleObject(child);
            }
        }
Example #30
0
    } //WriteExampleElement()

    // Write some example attributes
    public static void WriteExampleAttributes(XmlSchemaObjectCollection attributes, 
                                              XmlSchema myXmlSchema,
                                              XmlTextWriter myXmlTextWriter)
    {
      foreach(object o in attributes)
      {
        if (o is XmlSchemaAttribute)
        {
          WriteExampleAttribute((XmlSchemaAttribute)o, myXmlTextWriter);
        } //if
        else
        {
          XmlSchemaAttributeGroupRef xsagr = (XmlSchemaAttributeGroupRef)o;
          XmlSchemaAttributeGroup group = 
              (XmlSchemaAttributeGroup)myXmlSchema.AttributeGroups[xsagr.RefName];
          WriteExampleAttributes(group.Attributes, myXmlSchema, myXmlTextWriter);
        } //else
      } //foreach
    } //WriteExampleAttributes()
Example #31
0
        void ExportMembersMapSchema(XmlSchema schema, ClassMap map, XmlTypeMapping baseMap, XmlSchemaObjectCollection outAttributes, out XmlSchemaSequence particle, out XmlSchemaAnyAttribute anyAttribute)
        {
            particle = null;
            XmlSchemaSequence seq = new XmlSchemaSequence();

            ICollection members = map.ElementMembers;

            if (members != null && !map.HasSimpleContent)
            {
                foreach (XmlTypeMapMemberElement member in members)
                {
                    if (baseMap != null && DefinedInBaseMap(baseMap, member))
                    {
                        continue;
                    }

                    Type memType = member.GetType();
                    if (memType == typeof(XmlTypeMapMemberFlatList))
                    {
                        XmlSchemaParticle part = GetSchemaArrayElement(schema, member.ElementInfo);
                        if (part != null)
                        {
                            seq.Items.Add(part);
                        }
                    }
                    else if (memType == typeof(XmlTypeMapMemberAnyElement))
                    {
                        seq.Items.Add(GetSchemaArrayElement(schema, member.ElementInfo));
                    }
                    else if (memType == typeof(XmlTypeMapMemberElement))
                    {
                        GetSchemaElement(schema, (XmlTypeMapElementInfo)member.ElementInfo [0],
                                         member.DefaultValue, true, new XmlSchemaObjectContainer(seq));
                    }
                    else
                    {
                        GetSchemaElement(schema, (XmlTypeMapElementInfo)member.ElementInfo[0],
                                         true, new XmlSchemaObjectContainer(seq));
                    }
                }
            }

            if (seq.Items.Count > 0)
            {
                particle = seq;
            }

            // Write attributes

            ICollection attributes = map.AttributeMembers;

            if (attributes != null)
            {
                foreach (XmlTypeMapMemberAttribute attr in attributes)
                {
                    if (baseMap != null && DefinedInBaseMap(baseMap, attr))
                    {
                        continue;
                    }
                    outAttributes.Add(GetSchemaAttribute(schema, attr, true));
                }
            }

            XmlTypeMapMember anyAttrMember = map.DefaultAnyAttributeMember;

            if (anyAttrMember != null)
            {
                anyAttribute = new XmlSchemaAnyAttribute();
            }
            else
            {
                anyAttribute = null;
            }
        }
Example #32
0
 internal virtual void OnClear(XmlSchemaObjectCollection container) {}
Example #33
0
        public Control GetWebControl(System.Web.HttpServerUtility server, XmlNode renderingDocument)
        {
            PlaceHolder ph = new PlaceHolder();

            Label lbl = new Label();

            if (renderingDocument.Attributes["label"] != null)
            {
                lbl.Text = renderingDocument.Attributes["renderedLabel"].Value.FromXmlValue2Render(server);
            }
            else
            {
                lbl.Text = this.Name.FromXmlName2Render(server);
            }
            lbl.CssClass = "label";
            ph.Controls.Add(lbl);

            VEMapControl vem = new VEMapControl(this);

            if (renderingDocument.Attributes["class"] != null)
            {
                vem.CssClass = renderingDocument.Attributes["class"].Value.FromXmlValue2Render(server);
            }
            if (renderingDocument.Attributes["rel"] != null)
            {
                renderingDocument.Attributes["rel"].Value.FromXmlValue2Render(server);
            }
            if (renderingDocument.Attributes["description"] != null)
            {
                vem.ToolTip = renderingDocument.Attributes["description"].Value.FromXmlValue2Render(server);
            }

            ph.Controls.Add(vem);

            // Validators

            List <XmlSchemaElement> baseSchemaElements = Common.getElementsFromSchema(baseSchema);

            if (!baseSchemaElements[0].IsNillable)
            {
                RequiredFieldValidator rqfv = new RequiredFieldValidator();
                rqfv.ErrorMessage      = "Required fields shouldn't be empty";
                rqfv.ControlToValidate = vem.ID + "$latitude";
                rqfv.ValidationGroup   = "1";
                rqfv.Display           = ValidatorDisplay.Dynamic;
                ph.Controls.Add(rqfv);
            }
            if (!baseSchemaElements[1].IsNillable)
            {
                RequiredFieldValidator rqfv = new RequiredFieldValidator();
                rqfv.ErrorMessage      = "Required fields shouldn't be empty";
                rqfv.ControlToValidate = vem.ID + "$longitude";
                rqfv.Display           = ValidatorDisplay.Dynamic;
                ph.Controls.Add(rqfv);
                rqfv.ValidationGroup = "1";
            }

            // Setting up base validators
            // ( validators for min and max of latitude (-90,90) and longitude (-180,180) )

            CompareValidator maxLatitudeValidator = new CompareValidator();

            maxLatitudeValidator.ID = this.Name + "_maxLatitudeValidator";
            maxLatitudeValidator.ControlToValidate = vem.ID + "$latitude";;
            maxLatitudeValidator.Type            = ValidationDataType.Integer;
            maxLatitudeValidator.ValueToCompare  = "90";
            maxLatitudeValidator.Operator        = ValidationCompareOperator.LessThanEqual;
            maxLatitudeValidator.ErrorMessage    = "The value has to be lower than or equal to 90";
            maxLatitudeValidator.Text            = maxLatitudeValidator.ErrorMessage;
            maxLatitudeValidator.Display         = ValidatorDisplay.Dynamic;
            maxLatitudeValidator.Type            = ValidationDataType.Double;
            maxLatitudeValidator.ValidationGroup = "1";

            ph.Controls.Add(maxLatitudeValidator);

            CompareValidator minLatitudeValidator = new CompareValidator();

            minLatitudeValidator.ID = this.Name + "_minLatitudeValidator";
            minLatitudeValidator.ControlToValidate = vem.ID + "$latitude";;
            minLatitudeValidator.Type            = ValidationDataType.Integer;
            minLatitudeValidator.ValueToCompare  = "-90";
            minLatitudeValidator.Operator        = ValidationCompareOperator.GreaterThanEqual;
            minLatitudeValidator.ErrorMessage    = "The value has to be greater than or equal to -90";
            minLatitudeValidator.Text            = minLatitudeValidator.ErrorMessage;
            minLatitudeValidator.Display         = ValidatorDisplay.Dynamic;
            minLatitudeValidator.Type            = ValidationDataType.Double;
            minLatitudeValidator.ValidationGroup = "1";
            ph.Controls.Add(minLatitudeValidator);

            CompareValidator maxLongitudeValidator = new CompareValidator();

            maxLongitudeValidator.ID = this.Name + "_maxLongitudeValidator";
            maxLongitudeValidator.ControlToValidate = vem.ID + "$longitude";;
            maxLongitudeValidator.Type            = ValidationDataType.Integer;
            maxLongitudeValidator.ValueToCompare  = "180";
            maxLongitudeValidator.Operator        = ValidationCompareOperator.LessThanEqual;
            maxLongitudeValidator.ErrorMessage    = "The value has to be lower than or equal to 180";
            maxLongitudeValidator.Text            = maxLongitudeValidator.ErrorMessage;
            maxLongitudeValidator.Display         = ValidatorDisplay.Dynamic;
            maxLongitudeValidator.Type            = ValidationDataType.Double;
            maxLongitudeValidator.ValidationGroup = "1";
            ph.Controls.Add(maxLongitudeValidator);

            CompareValidator minLongitudeValidator = new CompareValidator();

            minLongitudeValidator.ID = this.Name + "_minLongitudeValidator";
            minLongitudeValidator.ControlToValidate = vem.ID + "$longitude";;
            minLongitudeValidator.Type            = ValidationDataType.Integer;
            minLongitudeValidator.ValueToCompare  = "-180";
            minLongitudeValidator.Operator        = ValidationCompareOperator.GreaterThanEqual;
            minLongitudeValidator.ErrorMessage    = "The value has to be greater than or equal to -180";
            minLongitudeValidator.Text            = minLongitudeValidator.ErrorMessage;
            minLongitudeValidator.Display         = ValidatorDisplay.Dynamic;
            minLongitudeValidator.Type            = ValidationDataType.Double;
            minLongitudeValidator.ValidationGroup = "1";
            ph.Controls.Add(minLongitudeValidator);

            // setting up latitude constraints
            if (((XmlSchemaSimpleType)baseSchemaElements[0].SchemaType) != null)
            {
                XmlSchemaObjectCollection latConstrColl =
                    ((XmlSchemaSimpleTypeRestriction)
                     ((XmlSchemaSimpleType)
                      baseSchemaElements[0]
                      .SchemaType).Content).Facets;

                foreach (XmlSchemaFacet facet in latConstrColl)
                {
                    // TODO
                    // No Contraints yet :D
                }
            }

            // setting up longitude constraints
            if (((XmlSchemaSimpleType)baseSchemaElements[1].SchemaType) != null)
            {
                XmlSchemaObjectCollection longConstrColl =
                    ((XmlSchemaSimpleTypeRestriction)
                     ((XmlSchemaSimpleType)
                      baseSchemaElements[1]
                      .SchemaType).Content).Facets;

                foreach (XmlSchemaFacet facet in longConstrColl)
                {
                    // TODO
                    // No Contraints yet :D
                }
            }

            // setting up custom constraints (close your eyes =)
            XmlSchemaComplexContentExtension cce = (XmlSchemaComplexContentExtension)((XmlSchemaComplexContent)(((XmlSchemaComplexType)baseSchema.Items[0])).ContentModel).Content;

            if (cce.Annotation != null)
            {
                foreach (XmlSchemaDocumentation sd in cce.Annotation.Items)
                {
                    XmlNode node = sd.Markup[0];
                    if (node.Name == "maxDistanceFrom")
                    {
                        double km, lat, lon;
                        if (double.TryParse(node.ChildNodes[0].InnerText, out km) &&
                            double.TryParse(node.ChildNodes[1].InnerText, out lat) &&
                            double.TryParse(node.ChildNodes[2].InnerText, out lon))
                        {
                            if (maxDistancesFrom == null)
                            {
                                maxDistancesFrom = new List <List <double> >();
                                ph.Controls.Add(getMaxDistanceValidator(vem.ID));
                            }
                            List <double> newDist = new List <double>();
                            newDist.Add(km);
                            newDist.Add(lat);
                            newDist.Add(lon);
                            maxDistancesFrom.Add(newDist);
                        }
                    }
                }
            }

            return(ph);
        }