Exemple #1
0
        /// <summary>
        /// Get properties of the specified type
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        public static PropertyInfo[] GetOrderedElementProperties(Type type)
        {
            var sequenceElements = new List <KeyValuePair <PropertyInfo, int> >();

            PropertyInfo[] prop = type.GetProperties();
            for (int i = 0; i < prop.Length; ++i)
            {
                PropertyInfo pi  = prop[i];
                var          atn = (CustomAttributeHelper.First <XsElementAttribute>(pi));
                if (atn == null || atn.Name.StartsWith("_", StringComparison.Ordinal))
                {
                    continue;
                }

                int order = (atn.Ordering) * 10000 + i;
                sequenceElements.Add(new KeyValuePair <PropertyInfo, int>(pi, order));
            }
            sequenceElements.Sort((x1, x2) => (x1.Value - x2.Value));
            PropertyInfo[] ret = new PropertyInfo[sequenceElements.Count];
            for (int i = 0; i < sequenceElements.Count; ++i)
            {
                ret[i] = sequenceElements[i].Key;
            }
            return(ret);
        }
Exemple #2
0
        /// Determine if the specified object is empty and should not be saved if <see cref="SkipIfEmpty"/> is set
        public bool IsEmpty(object value)
        {
            if (value == null)
            {
                return(true);
            }
            IEnumerable e = (value as IEnumerable);

            if (e != null)
            {
                IEnumerator en = e.GetEnumerator();
                if (en != null)
                {
                    if (!AtLeastOneChildForNotEmpty || en.MoveNext())
                    {
                        return(false);
                    }
                }
            }

            // element is not empty if it has a not empty sub-element
            var props = value.GetType().GetProperties();

            foreach (PropertyInfo c in props)
            {
                var ee = CustomAttributeHelper.First <XsElementAttribute>(c);
                if (ee != null && !ee.IsEmpty(c.GetValue(value, null)))
                {
                    return(false);
                }
            }

            // Or any non-empty attributes
            object defValue = null;

            foreach (PropertyInfo c in props)
            {
                var n = XsAttributeAttribute.GetNames(c, false);
                if (n == null)
                {
                    continue;
                }

                object v = c.GetValue(value, null);
                if (v != null)
                {
                    if (defValue == null)
                    {
                        defValue = Utils.CreateInstance(value.GetType());
                    }
                    object vdef = c.GetValue(defValue, null);
                    if (!v.Equals(vdef))
                    {
                        return(false);
                    }
                }
            }
            return(true);
        }
Exemple #3
0
        /// <summary>
        /// Write element to the output stream
        /// </summary>
        /// <param name="writer">Where to write</param>
        /// <param name="nameOverride">Local name to be used, or null if name should be retirevent from <see cref="XsTypeAttribute"/> of the type.</param>
        public virtual void WriteXml(XmlWriter writer, string nameOverride)
        {
            string namesp = null;

            if (nameOverride == null)
            {
                foreach (XsTypeAttribute a in CustomAttributeHelper.All <XsTypeAttribute>(GetType()))
                {
                    nameOverride = a.Name;
                    namesp       = a.Namespace;
                    break;
                }
                if (nameOverride == null)
                {
                    return;
                }
            }
            writer.WriteStartElement(nameOverride, namesp);

            WriteAttributes(writer);
            WriteText(writer);

            foreach (PropertyInfo c in GetOrderedElementProperties(GetType()))
            {
                object             v  = c.GetValue(this, null);
                IXsElement         o  = v as IXsElement;
                XsElementAttribute ab = CustomAttributeHelper.First <XsElementAttribute>(c);
                if (ab == null)
                {
                    continue;
                }
                if (ab.Name.Length == 0)
                {
                    IEnumerable e = (v as IEnumerable);
                    if (e != null)
                    {
                        foreach (IXsElement action in e)
                        {
                            if (action != null)
                            {
                                action.WriteXml(writer, ab.CollectionItemElementName);
                            }
                        }
                    }
                }
                else if (o != null && !(ab.SkipIfEmpty && ab.IsEmpty(v)))
                {
                    o.WriteXml(writer, ab.Name);
                }
            }

            writer.WriteEndElement();
        }
        /// <summary>
        /// Find action by ID
        /// </summary>
        /// <typeparam name="T">Type of action to search</typeparam>
        /// <param name="id">Action ID</param>
        /// <param name="throwIfNotFound">true if ScriptRuntimeException is thrown if the ID is not found</param>
        /// <returns>Found action or null, if not found</returns>
        public T Find <T>(string id, bool throwIfNotFound) where T : class, IScriptAction
        {
            T t = CallStack.FindTree <T>(id);

            if (throwIfNotFound && t == null)
            {
                var v = CustomAttributeHelper.First <XsTypeAttribute>(typeof(T));
                if (v == null || v.Name == null)
                {
                    throw new ScriptRuntimeException("Action with id='" + id + "' was not found");
                }
                throw new ScriptRuntimeException(v.Name + " with id='" + id + "' was not found");
            }
            return(t);
        }
Exemple #5
0
        /// Add action to the code
        public void Add(IScriptAction action)
        {
            string methodId;

            for (int n = 0; ; ++n)
            {
                if (string.IsNullOrEmpty(action.Id))
                {
                    methodId = "_" + CustomAttributeHelper.First <XsTypeAttribute>(action.GetType()).Name;
                }
                else
                {
                    methodId = action.Id;
                }
                if (n != 0)
                {
                    methodId += n;
                }
                if (!_methodNames.ContainsKey(methodId))
                {
                    _methodNames[methodId] = true;
                    break;
                }
            }
            if (action is Script || methodId == action.Id || action is Sub)
            {
                Methods.Add(action);
            }
            else
            {
                Sequence b = new Sequence {
                    Id = methodId
                };
                b.Add(action);
                Methods.Add(b);
                Value += Environment.NewLine + "{ object __ret=" + methodId + "_inline(); if (__ret!=null) return __ret;}";
            }
        }
        /// <summary>
        /// Returns a <see cref="System.String"/> that represents this instance.
        /// </summary>
        /// <returns>
        /// A <see cref="System.String"/> that represents this instance.
        /// </returns>
        public override string ToString()
        {
            StringBuilder   sb = new StringBuilder();
            XsTypeAttribute v  = CustomAttributeHelper.First <XsTypeAttribute>(GetType());

            if (_elementName != null)
            {
                sb.Append(_elementName);
            }
            else
            {
                sb.Append((v == null) ? GetType().FullName : v.Name);
            }
            sb.Append("(");

            bool first = true;

            if (!string.IsNullOrEmpty(Id))
            {
                sb.AppendFormat("id=\"{0}\"", Id);
                first = false;
            }
            object def = null;

            foreach (PropertyInfo pi in GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.SetProperty))
            {
                var n = XsAttributeAttribute.GetNames(pi, false);
                if (n == null || n[0] == "id" || n[0] == "password")
                {
                    continue;
                }

                object o = pi.GetValue(this, null);
                if (def == null)
                {
                    def = Utils.CreateInstance(GetType());
                }
                if (o == null || o.Equals(pi.GetValue(def, null)) || (n[0] == string.Empty && n.Length == 1))
                {
                    continue;
                }


                if (!first)
                {
                    sb.Append(", ");
                }

                first = false;
                sb.Append(n[0]);
                sb.Append("=");
                sb.Append("\"");
                string s = o.ToString().Trim();
                s = s.Replace("\r", "\\r");
                s = s.Replace("\n", "\\n");
                s = s.Replace("\t", "\\t");

                int maxW = (n[0] == "from" || n[0] == "location") ? 50 : 30;
                var fw   = (n[0] == "from" || n[0] == "location") ? FitWidthOption.EllipsisStart : FitWidthOption.EllipsisEnd;

                sb.Append(Utils.FitWidth(s, maxW, fw));
                sb.Append("\"");
            }

            sb.Append(")");
            return(sb.ToString());
        }
Exemple #7
0
        ///<summary>Generate XML schema for the given types
        ///</summary>
        ///<param name="ns">Default namespace</param>
        ///<param name="types">Types to include into schema</param>
        ///<param name="root">Root element</param>
        ///<param name="interfaces">Interface types</param>
        ///<returns>Built schema</returns>
        public static XmlSchema BuildSchema(string ns, Type[] types, Type root, Type[] interfaces)
        {
            XmlSchema xmlSchema = new XmlSchema();

            xmlSchema.Namespaces.Add("xsd", "http://www.w3.org/2001/XMLSchema");
            xmlSchema.Namespaces.Add("xsi", "http://www.w3.org/2001/XMLSchema-instance");
            xmlSchema.ElementFormDefault   = XmlSchemaForm.Qualified;
            xmlSchema.AttributeFormDefault = XmlSchemaForm.Unqualified;
            xmlSchema.Namespaces.Add("ns", ns);
            xmlSchema.TargetNamespace = ns;

            // Comment
            XmlSchemaAnnotation    annotation     = new XmlSchemaAnnotation();
            XmlSchemaDocumentation documentation  = new XmlSchemaDocumentation();
            XmlDocument            helperDocument = new XmlDocument();
            string comment = String.Format("  XML schema for {0} , generated at {1}  ", ns, DateTime.Now.ToString());

            documentation.Markup = new XmlNode[1] {
                helperDocument.CreateComment(comment)
            };
            annotation.Items.Add(documentation);
            xmlSchema.Items.Add(annotation);

            // Create group "action" to refer to any action
            var ints = new Dictionary <Type, XmlSchemaGroup>();

            if (interfaces != null)
            {
                foreach (var intf in interfaces)
                {
                    var action = new XmlSchemaGroup();
                    action.Name     = getXmlTypeName(intf);
                    action.Particle = new XmlSchemaChoice();
                    xmlSchema.Items.Add(action);
                    ints.Add(intf, action);
                }
            }

            Dictionary <Type, XmlSchemaType> xmlTypes = new Dictionary <Type, XmlSchemaType>();

            foreach (var type in types)
            {
                // If it does not have our XML header - skip it
                var na = (CustomAttributeHelper.First <XsTypeAttribute>(type));
                if (na == null)
                {
                    continue;
                }


                // Check if it is complex or simple
                XmlSchemaComplexType ct = new XmlSchemaComplexType();
                ct.Name = getXmlTypeName(type);


                XmlSchemaObjectCollection attr = createComplexType(type, ct, ns, ints);

                // Add the new element as an option to the "action" group
                foreach (var i in ints)
                {
                    bool isAction = (type.FindInterfaces((tp, nu) => tp == i.Key, null).Length != 0);
                    if (isAction)
                    {
                        foreach (var tp in CustomAttributeHelper.All <XsTypeAttribute>(type))
                        {
                            if (!string.IsNullOrEmpty(tp.Name))
                            {
                                i.Value.Particle.Items.Add(new XmlSchemaElement
                                {
                                    Name           = tp.Name,
                                    MinOccurs      = 0,
                                    SchemaTypeName = new XmlQualifiedName(ct.Name, ns)
                                });
                            }
                        }
                    }
                }

                // Work with attributes
                foreach (var o in generateAttributes(xmlSchema, type, xmlTypes, ns))
                {
                    attr.Add(o);
                }

                if (na.AnyAttribute)
                {
                    ct.AnyAttribute = new XmlSchemaAnyAttribute
                    {
                        ProcessContents = XmlSchemaContentProcessing.Skip
                    };
                }


                // Add type to the list
                xmlTypes.Add(type, ct);
                xmlSchema.Items.Add(ct);

                if (root.IsAssignableFrom(type))
                {
                    // Add all variations of Script names as element
                    foreach (var o in CustomAttributeHelper.All <XsTypeAttribute>(root))
                    {
                        xmlSchema.Items.Add(new XmlSchemaElement
                        {
                            Name           = o.Name,
                            SchemaTypeName = new XmlQualifiedName(xmlTypes[typeof(Script)].Name, ns)
                        });
                    }
                }
            }
            return(xmlSchema);
        }
Exemple #8
0
        private static List <XmlSchemaAttribute> generateAttributes(XmlSchema xmlSchema, Type type, Dictionary <Type, XmlSchemaType> xmlTypes, string ns)
        {
            var def = Utils.CreateInstance(type);
            var ret = new List <XmlSchemaAttribute>();

            foreach (var pi in type.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.SetProperty))
            {
                var attnames = XsAttributeAttribute.GetNames(pi, false);
                if (attnames == null)
                {
                    continue;
                }

                foreach (var nameAttr in attnames)
                {
                    if (string.IsNullOrEmpty(nameAttr))
                    {
                        continue;
                    }

                    XmlSchemaAttribute xsa = new XmlSchemaAttribute();
                    xsa.Name = nameAttr;

                    if (pi.PropertyType == typeof(bool))
                    {
                        xsa.SchemaTypeName = XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.Boolean).QualifiedName;
                    }
                    else if (pi.PropertyType == typeof(int))
                    {
                        xsa.SchemaTypeName = XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.Integer).QualifiedName;
                    }
                    else if (pi.PropertyType == typeof(float))
                    {
                        xsa.SchemaTypeName = XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.Float).QualifiedName;
                    }
                    else if (pi.PropertyType == typeof(double))
                    {
                        xsa.SchemaTypeName = XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.Double).QualifiedName;
                    }
                    else if (pi.PropertyType == typeof(uint))
                    {
                        xsa.SchemaTypeName = XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.UnsignedInt).QualifiedName;
                    }
                    else if (pi.PropertyType == typeof(ulong))
                    {
                        xsa.SchemaTypeName = XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.UnsignedLong).QualifiedName;
                    }
                    else if (pi.PropertyType == typeof(long))
                    {
                        xsa.SchemaTypeName = XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.Long).QualifiedName;
                    }
                    else if (pi.PropertyType == typeof(decimal))
                    {
                        xsa.SchemaTypeName = XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.Decimal).QualifiedName;
                    }
                    else if (pi.PropertyType.IsEnum)
                    {
                        if (!xmlTypes.ContainsKey(pi.PropertyType))
                        {
                            createEnum(pi, xmlTypes, xmlSchema);
                        }
                        xsa.SchemaTypeName = new XmlQualifiedName(xmlTypes[pi.PropertyType].Name, ns);
                    }
                    else if (pi.PropertyType == typeof(string))
                    {
                        xsa.SchemaTypeName = XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.String).QualifiedName;
                    }


                    var req = CustomAttributeHelper.First <XsRequiredAttribute>(pi);
                    if (req != null && (string.IsNullOrEmpty(req.Name) || req.Name == nameAttr))
                    {
                        xsa.Use = XmlSchemaUse.Required;
                    }
                    else
                    {
                        object v = pi.GetValue(def, null);
                        if (v != null)
                        {
                            string value = v.ToString();
                            if ((pi.PropertyType.IsPrimitive || pi.PropertyType.IsEnum))
                            {
                                value = (value.Substring(0, 1).ToLower() + value.Substring(1));
                            }
                            xsa.DefaultValue = value;
                        }
                    }

                    ret.Add(xsa);
                }
            }
            return(ret);
        }
Exemple #9
0
        private static XmlSchemaObjectCollection createComplexType(Type type, XmlSchemaComplexType ct, string ns, Dictionary <Type, XmlSchemaGroup> intfs)
        {
            ct.IsMixed = allowsText(type);

            XmlSchemaSequence sequence = new XmlSchemaSequence();

            foreach (var pi in XsElement.GetOrderedElementProperties(type))
            {
                var atn = (CustomAttributeHelper.First <XsElementAttribute>(pi));

                if (atn.CollectionItemType != null && intfs.ContainsKey(atn.CollectionItemType))
                {
                    sequence.Items.Add(new XmlSchemaGroupRef
                    {
                        MinOccurs       = 0,
                        MaxOccursString = "unbounded",
                        RefName         = new XmlQualifiedName(getXmlTypeName(atn.CollectionItemType), ns)
                    });
                }
                else if (atn.CollectionItemType == null)
                {
                    if (atn.Name == "")
                    {
                        sequence.Items.Add(new XmlSchemaAny
                        {
                            MinOccurs       = 0,
                            MaxOccursString = "unbounded",
                            ProcessContents = XmlSchemaContentProcessing.Skip
                        });
                    }
                    else
                    {
                        sequence.Items.Add(new XmlSchemaElement
                        {
                            MinOccurs      = 0,
                            MaxOccurs      = 1,
                            Name           = atn.Name,
                            SchemaTypeName = new XmlQualifiedName(getXmlTypeName(pi.PropertyType), ns)
                        });
                    }
                }
                else
                {
                    sequence.Items.Add(new XmlSchemaElement
                    {
                        MinOccurs       = 0,
                        MaxOccursString = "unbounded",
                        Name            = atn.CollectionItemElementName,
                        SchemaTypeName  = new XmlQualifiedName(getXmlTypeName(atn.CollectionItemType), ns)
                    });
                }
            }

            if (sequence.Items.Count > 0)
            {
                ct.Particle = sequence;
            }
            else
            {
                ct.Particle = null;
            }

            return(ct.Attributes);
        }