상속: Attribute
예제 #1
0
 public void SetAttributeAnimation(MapAttribute attribute, Animation animationInstance)
 {
     if (mAttributeAnimInstances.ContainsKey(attribute))
     {
         mAttributeAnimInstances[attribute] = animationInstance;
     }
 }
예제 #2
0
            public static void Postfix(GameMain __instance)
            {
                try
                {
                    String filePath = FindOverridenFile("GroundTypes");
                    if (filePath is null)
                    {
                        Log.Warning($"[{nameof(GameMain_ReadCSVData_MapAttribute)}] File not found: GroundTypes.json");
                        return;
                    }

                    Int32          language      = StWorkProxy.CurrentLanguage;
                    MapAttribute[] mapAttributes = StWorkProxy.MapAttribute;

                    foreach (Reference <TransifexEntry> item in PrepareTexts(filePath).Enumerate())
                    {
                        GroundTypeId reference = GroundTypeId.Parse(item.Key);
                        MapAttribute info      = mapAttributes[reference.Id];
                        info.name[language] = item.Value.Text;
                    }

                    Log.Message($"[{nameof(GameMain_ReadCSVData_MapAttribute)}] Loaded: GroundTypes.json");
                }
                catch (Exception ex)
                {
                    Log.Error(ex, $"[{nameof(GameMain_ReadCSVData_MapAttribute)}] Failed to load GroundTypes.json");
                }
            }
예제 #3
0
        static void LoadAndAssignValues(out Dictionary <string, T> stringToValue, out Dictionary <T, string> valueToString)
        {
            stringToValue = new Dictionary <string, T>();
            valueToString = new Dictionary <T, string>();
#if PORTABLE
            var fields = typeof(T).GetTypeInfo().DeclaredFields.ToArray();
#else
            var fields = typeof(T).GetFields();
#endif

            for (int i = fields.Length - 1; i >= 0; --i)
            {
                var          field       = fields[i];
                MapAttribute cssNameAttr = null;
#if PORTABLE
                var customAttrs = field.GetCustomAttributes(mapNameAttrType, false).ToArray();
#else
                var customAttrs = field.GetCustomAttributes(mapNameAttrType, false);
#endif
                if (customAttrs != null && customAttrs.Length > 0 &&
                    (cssNameAttr = customAttrs[0] as MapAttribute) != null)
                {
                    T value = (T)field.GetValue(null);
                    stringToValue.Add(cssNameAttr.Name, value); //1.
                    valueToString.Add(value, cssNameAttr.Name); //2.
                }
            }
        }
예제 #4
0
        /// <summary>
        /// Gets all available MapElementTypes. Returns an empty list if none found. It will never return null or a list with null elements.
        /// <p>The actual table names used in the queries are obtained from the tableNames dictionary.</p>
        /// <p><strong>Implementation Notes</strong></p>
        /// <ul type="disc">
        /// <li>Get instance of IDbConnection from ConnectionManager with&nbsp;this.connectionName</li>
        /// <li>Perform query to obtain all records from elementTypes</li>
        /// <li>For each retrieved record, construct a new MapElementType and fill it with the row info</li>
        /// <li>Perform query to obtain all rows from attributes whose owner_id is in the set of elementType IDs</li>
        /// <li>For each retrieved record, assemble it into a MapAttribute and add to the appropriate MapElementType</li>
        /// <li>Close connection and return the list of available MapElementTypes</li>
        /// </ul>             /// </summary>
        /// <exception>MapDataSourceException If there were errors during this operation</exception>
        /// <returns>List of available MapElementTypes</returns>
        public IList <MapElementType> DownloadElementTypes()
        {
            IList <MapElementType> result   = null;
            MapElementType         elemType = null;
            IDictionary <long, IList <MapAttribute> > attrsDict = null;
            IList <MapAttribute> attrs = null;
            MapAttribute         attr  = null;

            using (IDbConnection connection = CreateConnection("Sql1"))
            {
                connection.Open();

                using (IDataReader reader = Helper.ExecuteReader(connection, queryTextElementTypes))
                {
                    result = new List <MapElementType>();
                    while (reader.Read())
                    {
                        elemType       = new MapElementType();
                        elemType.Id    = reader.GetInt32(0);
                        elemType.Name  = reader.GetString(1);
                        elemType.Layer = reader.GetInt32(2);

                        result.Add(elemType);
                    }
                }
                attrsDict = new Dictionary <long, IList <MapAttribute> >();
                foreach (MapElementType type in result)
                {
                    if (attrsDict.ContainsKey(type.Id))
                    {
                        type.Attributes = attrsDict[type.Id];
                    }
                    else
                    {
                        using (IDataReader reader = Helper.ExecuteReader(connection, "SELECT * FROM attribs where owner_id = " + type.Id))
                        {
                            attrs = new List <MapAttribute>();
                            while (reader.Read())
                            {
                                attr             = new MapAttribute();
                                attr.Id          = reader.GetInt32(0);
                                attr.OwnerId     = reader.GetInt32(1);
                                attr.OwnerType   = reader.GetString(2);
                                attr.Type        = reader.GetString(3);
                                attr.Name        = reader.GetString(4);
                                attr.IntValue    = reader.GetInt32(5);
                                attr.StringValue = reader.GetValue(6) as string;
                            }
                            type.Attributes    = attrs;
                            attrsDict[type.Id] = attrs;
                        }
                    }
                }
            }


            // your code here
            return(result);
        }
예제 #5
0
        public static int Resolve(this TargetMap value, int factionId)
        {
            MapAttribute mapAttribute = value.smethod_0 <MapAttribute>();

            if (mapAttribute != null && mapAttribute.ByFaction != 0)
            {
                return(MapUtils.smethod_12(mapAttribute.ByFaction, factionId));
            }
            return((int)value);
        }
예제 #6
0
        public static string GetName(this TargetMap value)
        {
            MapAttribute mapAttribute = value.smethod_0 <MapAttribute>();

            if (mapAttribute != null)
            {
                return(mapAttribute.Name);
            }
            return(value.ToString());
        }
예제 #7
0
        public static void Create()
        {
            var attribute = new MapAttribute(typeof(MapFromAttributeTests), typeof(MapToAttributeTests));

            Assert.Multiple(() =>
            {
                Assert.That(attribute.Source, Is.EqualTo(typeof(MapFromAttributeTests)));
                Assert.That(attribute.Destination, Is.EqualTo(typeof(MapToAttributeTests)));
            });
        }
예제 #8
0
        /// <summary>
        /// Get map name of object's key field
        /// </summary>
        /// <param name="objType">Object type</param>
        /// <returns>Key field map name or null if no key was found</returns>
        public string GetKeyMapName(System.Type objType)
        {
            PropertyInfo keyField = GetPropertyWithAttr(objType, typeof(PrimaryKeyAttribute));

            if (keyField != null)
            {
                MapAttribute mapAttribute = GetPropertyAttribute(objType, keyField, typeof(MapAttribute)) as MapAttribute;
                return(mapAttribute == null? keyField.Name : mapAttribute.MapName);
            }
            return(null);
        }
        public MapAttribute PlaceAttribute(MapBase mapDescriptor, int x, int y, MapAttribute attribute = null)
        {
            if (attribute == null)
            {
                attribute = CreateAttribute();
            }

            mapDescriptor.Attributes[x, y] = attribute;

            return(attribute);
        }
예제 #10
0
        public static IEnumerable <T> Read <T>(string path, Map map, IInputDriver driver)
            where T : new()
        {
            var reader = driver.GetReader(path, null);
            List <Assignment> assignments = new List <Assignment>();

            FieldInfo[] fields = typeof(T).GetFields();

            foreach (FieldInfo field in fields)
            {
                MapAttribute attribute = (MapAttribute)field.GetCustomAttributes(typeof(MapAttribute), false).FirstOrDefault();
                if (attribute != null)
                {
                    Assignment assignment = null;
                    var        entries    = map.Columns.Where(e => e.Value == field.Name);
                    foreach (var entry in entries)
                    {
                        int index = reader.FirstRow.IndexOf(entry.Key);
                        if (index >= 0)
                        {
                            assignment = new Assignment(index, field);
                            break;
                        }
                    }

                    if (assignment == null && attribute.Required)
                    {
                        throw new Exception("A \"" + field.Name + "\" mező nem található a térképben vagy a fájlban.");
                    }
                    else if (assignment != null)
                    {
                        Translation translation = null;
                        if (map.Enums.ContainsKey(field.Name))
                        {
                            translation = map.Enums[field.Name];
                        }
                        assignment.Cast = Transform.ToType(field.FieldType, translation);
                        assignments.Add(assignment);
                    }
                }
            }

            foreach (var record in reader.Skip(1))
            {
                T obj = new T();
                foreach (var assignment in assignments)
                {
                    assignment.Field.SetValue(obj, assignment.Cast(record[assignment.Index]));
                }
                yield return(obj);
            }

            reader.Dispose();
        }
예제 #11
0
            static void ShowPropertiesBlock <T>(T obj, IEnumerable <PropertyInfo> propsInfo, Int32 maxTypeTitleLen, Int32 maxPropTitleLen, Int32 maxPropTypeLen, Int32 maxPropNameLen, String indent, Boolean showMapingsOrRemarks)
            {
                foreach (var p in propsInfo)
                {
                    CreatioPropAttribute creatioPropAttr = (CreatioPropAttribute)p.GetCustomAttribute(typeof(CreatioPropAttribute), false);
                    MapAttribute         mapPropAttr     = (MapAttribute)p.GetCustomAttribute(typeof(MapAttribute));
                    MapRemarksAttribute  mapRem          = (MapRemarksAttribute)p.GetCustomAttribute(typeof(MapRemarksAttribute));

                    String propValue = p.GetValue(obj)?.ToString();
                    if (p.GetValue(obj) == null)
                    {
                        propValue = "---";
                    }
                    else if (p.PropertyType != typeof(String) && typeof(ICollection).IsAssignableFrom(p.PropertyType))
                    {
                        var val = (ICollection)p.GetValue(obj);
                        propValue = $"{val.Count} шт.";
                    }
                    else if (p.PropertyType == typeof(Guid) || p.PropertyType == typeof(Guid?))
                    {
                        Guid val = (Guid)p.GetValue(obj);
                        propValue = default(Guid) == (Guid)p.GetValue(obj) ? "---" : val.ToString();
                    }
                    else if (p.PropertyType == typeof(DateTime) || p.PropertyType == typeof(DateTime?))
                    {
                        DateTime val = (DateTime)p.GetValue(obj);
                        propValue = default(DateTime) == (DateTime)p.GetValue(obj) ? "---" : val.ToString();
                    }

                    if (showMapingsOrRemarks && (mapPropAttr != null || mapRem != null))
                    {
                        Console.ForegroundColor = ConsoleColor.DarkGreen;
                        Console.Write($"{indent}│   │");
                        if (mapPropAttr != null)
                        {
                            Console.Write($"   ~ {mapPropAttr}");
                        }
                        if (mapRem != null)
                        {
                            Console.Write($"   // {mapRem}");
                        }
                        Console.WriteLine();
                    }

                    String mapIsImplemented = $"│ {(mapPropAttr is null ? " " : mapPropAttr.Implemented ? "V" : "X")} │";

                    Console.ForegroundColor = creatioPropAttr?.Color ?? ConsoleColor.DarkGray;
                    var propType = GetCreatioTypeName(p);

                    Console.WriteLine($"{indent}{mapIsImplemented} {(String.IsNullOrEmpty(propType) ? "---" : propType).PadRight(maxTypeTitleLen)} │ {(creatioPropAttr?.CreatioTitle ?? "---").PadRight(maxPropTitleLen)} " +
                                      $"│ {GetTypeName(p).PadRight(maxPropTypeLen)} │ {p.Name.PadRight(maxPropNameLen)} │ {propValue}");
                }
                Console.ResetColor();
            }
예제 #12
0
    public static void Create()
    {
        var attribute = new MapAttribute(typeof(MapFromAttributeTests), typeof(MapToAttributeTests));

        Assert.Multiple(() =>
        {
            Assert.That(attribute.Source, Is.EqualTo(typeof(MapFromAttributeTests)));
            Assert.That(attribute.Destination, Is.EqualTo(typeof(MapToAttributeTests)));
            Assert.That(attribute.ContainingNamespaceKind, Is.EqualTo(ContainingNamespaceKind.Source));
            Assert.That(attribute.MatchingPropertyTypeKind, Is.EqualTo(MatchingPropertyTypeKind.Implicit));
        });
    }
예제 #13
0
        /// <summary>
        /// <para>
        /// Creates a path attribute.
        /// </para>
        /// </summary>
        ///
        /// <param name="id">the attribute id</param>
        /// <param name="ownerId">the attribute owner id</param>
        /// <param name="value">the value of the attribute</param>
        ///
        /// <returns>
        /// a new <see cref="MapAttribute"/> with specified parameters.
        /// </returns>
        private static MapAttribute CreatePathAttribute(int id, int ownerId, string value)
        {
            MapAttribute attribute = new MapAttribute();

            attribute.Id        = id;
            attribute.OwnerId   = ownerId;
            attribute.OwnerType = "Link";
            attribute.Name      = "path";

            attribute.Type        = "string";
            attribute.StringValue = value;

            return(attribute);
        }
예제 #14
0
        //Attribute/Animations
        public Animation GetAttributeAnimation(MapAttribute attr, Guid animId)
        {
            if (attr == null)
            {
                return(null);
            }

            if (!mAttributeAnimInstances.ContainsKey(attr))
            {
                mAttributeAnimInstances.Add(attr, new Animation(AnimationBase.Get(animId), true));
            }

            return(mAttributeAnimInstances[attr]);
        }
예제 #15
0
        /// <summary>构造函数</summary>
        /// <param name="table"></param>
        /// <param name="property">属性</param>
        public FieldItem(TableItem table, PropertyInfo property)
        {
            Table = table;

            if (property != null)
            {
                _Property = property;
                var dc = _Column = BindColumnAttribute.GetCustomAttribute(property);
                var df = _DataObjectField = property.GetCustomAttribute<DataObjectFieldAttribute>();
                var ds = _Description = property.GetCustomAttribute<DescriptionAttribute>();
                var di = _DisplayName = property.GetCustomAttribute<DisplayNameAttribute>();
                Map = property.GetCustomAttribute<MapAttribute>();
                Name = property.Name;
                Type = property.PropertyType;
                DeclaringType = property.DeclaringType;

                if (df != null)
                {
                    IsIdentity = df.IsIdentity;
                    PrimaryKey = df.PrimaryKey;
                    IsNullable = df.IsNullable;
                    Length = df.Length;

                    IsDataObjectField = true;
                }

                if (dc != null)
                {
                    Master = dc.Master;
                }

                if (dc != null && !dc.Name.IsNullOrWhiteSpace())
                    ColumnName = dc.Name;
                else
                    ColumnName = Name;

                if (ds != null && !String.IsNullOrEmpty(ds.Description))
                    Description = ds.Description;
                else if (dc != null && !String.IsNullOrEmpty(dc.Description))
                    Description = dc.Description;
                if (di != null && !di.DisplayName.IsNullOrEmpty())
                    DisplayName = di.DisplayName;

                var map = Map;
                if (map == null || map.Provider == null) ReadOnly = !property.CanWrite;
                var ra = property.GetCustomAttribute<ReadOnlyAttribute>();
                if (ra != null) ReadOnly = ra.IsReadOnly;
            }
        }
예제 #16
0
        /// <summary>
        /// Creates a new link between the startNode and the endNode.
        /// The startPort and endPort are the ports for the start and end nodes.
        /// </summary>
        /// <param name="startNode">The starting node</param>
        /// <param name="endNode">The ending node</param>
        /// <param name="startPort">The starting port</param>
        /// <param name="endPort">the ending port</param>
        /// <param name="mapdata">The Mapdata to use for generating the unique id of the link.</param>
        /// <param name="origLink">The original link</param>
        /// <param name="toBeAddedLinks">The number of links yet to be added.</param>
        /// <returns>The new link created.</returns>
        private MapLink CreateNewLink(
            MapNode startNode, MapNode endNode, MapPort startPort, MapPort endPort, MapData mapdata,
            MapLink origLink, int toBeAddedLinks)
        {
            //Create new link
            long    newLinkId = GetUniqueId(typeof(MapLink), mapdata, toBeAddedLinks);
            MapLink newLink   = new MapLink();

            newLink.Id   = newLinkId;
            newLink.Name = MapLinkNamePrefix + newLinkId;

            //Add the nodes
            newLink.AddNode(startNode);
            newLink.AddNode(endNode);

            //Add the ports
            newLink.AddPort(startPort);
            newLink.AddPort(endPort);

            //Copy attributes of original link and set owner id of the new attributes. Also add to mapdata
            CopyAttributes(origLink, newLink, newLinkId, mapdata);

            //create a new attribute to store the original link id
            MapAttribute origLinkIdAttr = new MapAttribute();

            origLinkIdAttr.Name        = "origLinkId";
            origLinkIdAttr.StringValue = origLink.Id.ToString();
            long newAttrId = GetUniqueId(typeof(MapAttribute), mapdata, 0);

            origLinkIdAttr.Id        = newAttrId;
            origLinkIdAttr.OwnerType = "link";
            origLinkIdAttr.OwnerId   = newLink.Id;
            origLinkIdAttr.Type      = AttrTypeString;

            //Add the new attribute to the new link and the map data
            newLink.Attributes.Add(origLinkIdAttr);
            mapdata.AddAttribute(origLinkIdAttr);

            //Set new link's element type from original link
            newLink.ElementType = origLink.ElementType;

            return(newLink);
        }
예제 #17
0
        /// <summary>
        /// Copies the attributes of an old link to a new one.
        /// </summary>
        /// <param name="origLink">The old link</param>
        /// <param name="newLink">The new link</param>
        /// <param name="newLinkId">The id of the new link</param>
        /// <param name="mapdata">The mapdata into which the new attributes will be added.</param>
        private void CopyAttributes(MapLink origLink, MapLink newLink, long newLinkId, MapData mapdata)
        {
            foreach (MapAttribute attr in origLink.Attributes)
            {
                //Create a new attribute and set its properties
                MapAttribute newattr = new MapAttribute();
                newattr.Id            = GetUniqueId(typeof(MapAttribute), mapdata, 0);
                newattr.OwnerId       = newLinkId;
                newattr.Name          = attr.Name;
                newattr.OwnerType     = attr.OwnerType;
                newattr.Type          = attr.Type;
                newattr.IntValue      = attr.IntValue;
                newattr.StringValue   = attr.StringValue;
                newattr.DoubleValue   = attr.DoubleValue;
                newattr.DateTimeValue = attr.DateTimeValue;

                //Add new attribute to the new link
                newLink.AddAttribute(newattr);

                //Add new attribute to the new mapdata
                mapdata.AddAttribute(newattr);
            }
        }
예제 #18
0
        /// <summary> Write a Map XML Element from attributes in a member. </summary>
        public virtual void WriteMap(System.Xml.XmlWriter writer, System.Reflection.MemberInfo member, MapAttribute attribute, BaseAttribute parentAttribute, System.Type mappedClass)
        {
            writer.WriteStartElement( "map" );
            // Attribute: <name>
            writer.WriteAttributeString("name", attribute.Name==null ? DefaultHelper.Get_Map_Name_DefaultValue(member) : GetAttributeValue(attribute.Name, mappedClass));
            // Attribute: <access>
            if(attribute.Access != null)
            writer.WriteAttributeString("access", GetAttributeValue(attribute.Access, mappedClass));
            // Attribute: <table>
            if(attribute.Table != null)
            writer.WriteAttributeString("table", GetAttributeValue(attribute.Table, mappedClass));
            // Attribute: <schema>
            if(attribute.Schema != null)
            writer.WriteAttributeString("schema", GetAttributeValue(attribute.Schema, mappedClass));
            // Attribute: <catalog>
            if(attribute.Catalog != null)
            writer.WriteAttributeString("catalog", GetAttributeValue(attribute.Catalog, mappedClass));
            // Attribute: <subselect>
            if(attribute.Subselect != null)
            writer.WriteAttributeString("subselect", GetAttributeValue(attribute.Subselect, mappedClass));
            // Attribute: <lazy>
            if(attribute.Lazy != CollectionLazy.Unspecified)
            writer.WriteAttributeString("lazy", GetXmlEnumValue(typeof(CollectionLazy), attribute.Lazy));
            // Attribute: <inverse>
            if( attribute.InverseSpecified )
            writer.WriteAttributeString("inverse", attribute.Inverse ? "true" : "false");
            // Attribute: <mutable>
            if( attribute.MutableSpecified )
            writer.WriteAttributeString("mutable", attribute.Mutable ? "true" : "false");
            // Attribute: <cascade>
            if(attribute.Cascade != null)
            writer.WriteAttributeString("cascade", GetAttributeValue(attribute.Cascade, mappedClass));
            // Attribute: <order-by>
            if(attribute.OrderBy != null)
            writer.WriteAttributeString("order-by", GetAttributeValue(attribute.OrderBy, mappedClass));
            // Attribute: <where>
            if(attribute.Where != null)
            writer.WriteAttributeString("where", GetAttributeValue(attribute.Where, mappedClass));
            // Attribute: <batch-size>
            if(attribute.BatchSize != -9223372036854775808)
            writer.WriteAttributeString("batch-size", attribute.BatchSize.ToString());
            // Attribute: <outer-join>
            if(attribute.OuterJoin != OuterJoinStrategy.Unspecified)
            writer.WriteAttributeString("outer-join", GetXmlEnumValue(typeof(OuterJoinStrategy), attribute.OuterJoin));
            // Attribute: <fetch>
            if(attribute.Fetch != CollectionFetchMode.Unspecified)
            writer.WriteAttributeString("fetch", GetXmlEnumValue(typeof(CollectionFetchMode), attribute.Fetch));
            // Attribute: <persister>
            if(attribute.Persister != null)
            writer.WriteAttributeString("persister", GetAttributeValue(attribute.Persister, mappedClass));
            // Attribute: <collection-type>
            if(attribute.CollectionType != null)
            writer.WriteAttributeString("collection-type", GetAttributeValue(attribute.CollectionType, mappedClass));
            // Attribute: <check>
            if(attribute.Check != null)
            writer.WriteAttributeString("check", GetAttributeValue(attribute.Check, mappedClass));
            // Attribute: <optimistic-lock>
            if( attribute.OptimisticLockSpecified )
            writer.WriteAttributeString("optimistic-lock", attribute.OptimisticLock ? "true" : "false");
            // Attribute: <node>
            if(attribute.Node != null)
            writer.WriteAttributeString("node", GetAttributeValue(attribute.Node, mappedClass));
            // Attribute: <embed-xml>
            if( attribute.EmbedXmlSpecified )
            writer.WriteAttributeString("embed-xml", attribute.EmbedXml ? "true" : "false");
            // Attribute: <generic>
            if( attribute.GenericSpecified )
            writer.WriteAttributeString("generic", attribute.Generic ? "true" : "false");
            // Attribute: <sort>
            if(attribute.Sort != null)
            writer.WriteAttributeString("sort", GetAttributeValue(attribute.Sort, mappedClass));

            WriteUserDefinedContent(writer, member, null, attribute);

            System.Collections.ArrayList memberAttribs = GetSortedAttributes(member);
            int attribPos; // Find the position of the MapAttribute (its <sub-element>s must be after it)
            for(attribPos=0; attribPos<memberAttribs.Count; attribPos++)
                if( memberAttribs[attribPos] is MapAttribute
                    && ((BaseAttribute)memberAttribs[attribPos]).Position == attribute.Position )
                    break; // found
            int i = attribPos + 1;

            // Element: <meta>
            for(; i<memberAttribs.Count; i++)
            {
                BaseAttribute memberAttrib = memberAttribs[i] as BaseAttribute;
                if( IsNextElement(memberAttrib, parentAttribute, attribute.GetType())
                    || IsNextElement(memberAttrib, attribute, typeof(MetaAttribute)) )
                    break; // next attributes are 'elements' of the same level OR for 'sub-elements'
                else
                {
                    if( memberAttrib is MapAttribute )
                        break; // Following attributes are for this Map
                    if( memberAttrib is MetaAttribute )
                        WriteMeta(writer, member, memberAttrib as MetaAttribute, attribute, mappedClass);
                }
            }
            WriteUserDefinedContent(writer, member, typeof(MetaAttribute), attribute);
            // Element: <subselect>
            for(; i<memberAttribs.Count; i++)
            {
                BaseAttribute memberAttrib = memberAttribs[i] as BaseAttribute;
                if( IsNextElement(memberAttrib, parentAttribute, attribute.GetType())
                    || IsNextElement(memberAttrib, attribute, typeof(SubselectAttribute)) )
                    break; // next attributes are 'elements' of the same level OR for 'sub-elements'
                else
                {
                    if( memberAttrib is MapAttribute )
                        break; // Following attributes are for this Map
                    if( memberAttrib is SubselectAttribute )
                        WriteSubselect(writer, member, memberAttrib as SubselectAttribute, attribute, mappedClass);
                }
            }
            WriteUserDefinedContent(writer, member, typeof(SubselectAttribute), attribute);
            // Element: <cache>
            for(; i<memberAttribs.Count; i++)
            {
                BaseAttribute memberAttrib = memberAttribs[i] as BaseAttribute;
                if( IsNextElement(memberAttrib, parentAttribute, attribute.GetType())
                    || IsNextElement(memberAttrib, attribute, typeof(CacheAttribute)) )
                    break; // next attributes are 'elements' of the same level OR for 'sub-elements'
                else
                {
                    if( memberAttrib is MapAttribute )
                        break; // Following attributes are for this Map
                    if( memberAttrib is CacheAttribute )
                        WriteCache(writer, member, memberAttrib as CacheAttribute, attribute, mappedClass);
                }
            }
            WriteUserDefinedContent(writer, member, typeof(CacheAttribute), attribute);
            // Element: <synchronize>
            for(; i<memberAttribs.Count; i++)
            {
                BaseAttribute memberAttrib = memberAttribs[i] as BaseAttribute;
                if( IsNextElement(memberAttrib, parentAttribute, attribute.GetType())
                    || IsNextElement(memberAttrib, attribute, typeof(SynchronizeAttribute)) )
                    break; // next attributes are 'elements' of the same level OR for 'sub-elements'
                else
                {
                    if( memberAttrib is MapAttribute )
                        break; // Following attributes are for this Map
                    if( memberAttrib is SynchronizeAttribute )
                        WriteSynchronize(writer, member, memberAttrib as SynchronizeAttribute, attribute, mappedClass);
                }
            }
            WriteUserDefinedContent(writer, member, typeof(SynchronizeAttribute), attribute);
            // Element: <comment>
            for(; i<memberAttribs.Count; i++)
            {
                BaseAttribute memberAttrib = memberAttribs[i] as BaseAttribute;
                if( IsNextElement(memberAttrib, parentAttribute, attribute.GetType())
                    || IsNextElement(memberAttrib, attribute, typeof(CommentAttribute)) )
                    break; // next attributes are 'elements' of the same level OR for 'sub-elements'
                else
                {
                    if( memberAttrib is MapAttribute )
                        break; // Following attributes are for this Map
                    if( memberAttrib is CommentAttribute )
                        WriteComment(writer, member, memberAttrib as CommentAttribute, attribute, mappedClass);
                }
            }
            WriteUserDefinedContent(writer, member, typeof(CommentAttribute), attribute);
            // Element: <key>
            for(; i<memberAttribs.Count; i++)
            {
                BaseAttribute memberAttrib = memberAttribs[i] as BaseAttribute;
                if( IsNextElement(memberAttrib, parentAttribute, attribute.GetType())
                    || IsNextElement(memberAttrib, attribute, typeof(KeyAttribute)) )
                    break; // next attributes are 'elements' of the same level OR for 'sub-elements'
                else
                {
                    if( memberAttrib is MapAttribute )
                        break; // Following attributes are for this Map
                    if( memberAttrib is KeyAttribute )
                        WriteKey(writer, member, memberAttrib as KeyAttribute, attribute, mappedClass);
                }
            }
            WriteUserDefinedContent(writer, member, typeof(KeyAttribute), attribute);
            // Element: <map-key>
            for(; i<memberAttribs.Count; i++)
            {
                BaseAttribute memberAttrib = memberAttribs[i] as BaseAttribute;
                if( IsNextElement(memberAttrib, parentAttribute, attribute.GetType())
                    || IsNextElement(memberAttrib, attribute, typeof(MapKeyAttribute)) )
                    break; // next attributes are 'elements' of the same level OR for 'sub-elements'
                else
                {
                    if( memberAttrib is MapAttribute )
                        break; // Following attributes are for this Map
                    if( memberAttrib is MapKeyAttribute )
                        WriteMapKey(writer, member, memberAttrib as MapKeyAttribute, attribute, mappedClass);
                }
            }
            WriteUserDefinedContent(writer, member, typeof(MapKeyAttribute), attribute);
            // Element: <composite-map-key>
            for(; i<memberAttribs.Count; i++)
            {
                BaseAttribute memberAttrib = memberAttribs[i] as BaseAttribute;
                if( IsNextElement(memberAttrib, parentAttribute, attribute.GetType())
                    || IsNextElement(memberAttrib, attribute, typeof(CompositeMapKeyAttribute)) )
                    break; // next attributes are 'elements' of the same level OR for 'sub-elements'
                else
                {
                    if( memberAttrib is MapAttribute )
                        break; // Following attributes are for this Map
                    if( memberAttrib is CompositeMapKeyAttribute )
                        WriteCompositeMapKey(writer, member, memberAttrib as CompositeMapKeyAttribute, attribute, mappedClass);
                }
            }
            WriteUserDefinedContent(writer, member, typeof(CompositeMapKeyAttribute), attribute);
            // Element: <map-key-many-to-many>
            for(; i<memberAttribs.Count; i++)
            {
                BaseAttribute memberAttrib = memberAttribs[i] as BaseAttribute;
                if( IsNextElement(memberAttrib, parentAttribute, attribute.GetType())
                    || IsNextElement(memberAttrib, attribute, typeof(MapKeyManyToManyAttribute)) )
                    break; // next attributes are 'elements' of the same level OR for 'sub-elements'
                else
                {
                    if( memberAttrib is MapAttribute )
                        break; // Following attributes are for this Map
                    if( memberAttrib is MapKeyManyToManyAttribute )
                        WriteMapKeyManyToMany(writer, member, memberAttrib as MapKeyManyToManyAttribute, attribute, mappedClass);
                }
            }
            WriteUserDefinedContent(writer, member, typeof(MapKeyManyToManyAttribute), attribute);
            // Element: <index>
            for(; i<memberAttribs.Count; i++)
            {
                BaseAttribute memberAttrib = memberAttribs[i] as BaseAttribute;
                if( IsNextElement(memberAttrib, parentAttribute, attribute.GetType())
                    || IsNextElement(memberAttrib, attribute, typeof(IndexAttribute)) )
                    break; // next attributes are 'elements' of the same level OR for 'sub-elements'
                else
                {
                    if( memberAttrib is MapAttribute )
                        break; // Following attributes are for this Map
                    if( memberAttrib is IndexAttribute )
                        WriteIndex(writer, member, memberAttrib as IndexAttribute, attribute, mappedClass);
                }
            }
            WriteUserDefinedContent(writer, member, typeof(IndexAttribute), attribute);
            // Element: <composite-index>
            for(; i<memberAttribs.Count; i++)
            {
                BaseAttribute memberAttrib = memberAttribs[i] as BaseAttribute;
                if( IsNextElement(memberAttrib, parentAttribute, attribute.GetType())
                    || IsNextElement(memberAttrib, attribute, typeof(CompositeIndexAttribute)) )
                    break; // next attributes are 'elements' of the same level OR for 'sub-elements'
                else
                {
                    if( memberAttrib is MapAttribute )
                        break; // Following attributes are for this Map
                    if( memberAttrib is CompositeIndexAttribute )
                        WriteCompositeIndex(writer, member, memberAttrib as CompositeIndexAttribute, attribute, mappedClass);
                }
            }
            WriteUserDefinedContent(writer, member, typeof(CompositeIndexAttribute), attribute);
            // Element: <index-many-to-many>
            for(; i<memberAttribs.Count; i++)
            {
                BaseAttribute memberAttrib = memberAttribs[i] as BaseAttribute;
                if( IsNextElement(memberAttrib, parentAttribute, attribute.GetType())
                    || IsNextElement(memberAttrib, attribute, typeof(IndexManyToManyAttribute)) )
                    break; // next attributes are 'elements' of the same level OR for 'sub-elements'
                else
                {
                    if( memberAttrib is MapAttribute )
                        break; // Following attributes are for this Map
                    if( memberAttrib is IndexManyToManyAttribute )
                        WriteIndexManyToMany(writer, member, memberAttrib as IndexManyToManyAttribute, attribute, mappedClass);
                }
            }
            WriteUserDefinedContent(writer, member, typeof(IndexManyToManyAttribute), attribute);
            // Element: <index-many-to-any>
            for(; i<memberAttribs.Count; i++)
            {
                BaseAttribute memberAttrib = memberAttribs[i] as BaseAttribute;
                if( IsNextElement(memberAttrib, parentAttribute, attribute.GetType())
                    || IsNextElement(memberAttrib, attribute, typeof(IndexManyToAnyAttribute)) )
                    break; // next attributes are 'elements' of the same level OR for 'sub-elements'
                else
                {
                    if( memberAttrib is MapAttribute )
                        break; // Following attributes are for this Map
                    if( memberAttrib is IndexManyToAnyAttribute )
                        WriteIndexManyToAny(writer, member, memberAttrib as IndexManyToAnyAttribute, attribute, mappedClass);
                }
            }
            WriteUserDefinedContent(writer, member, typeof(IndexManyToAnyAttribute), attribute);
            // Element: <element>
            for(; i<memberAttribs.Count; i++)
            {
                BaseAttribute memberAttrib = memberAttribs[i] as BaseAttribute;
                if( IsNextElement(memberAttrib, parentAttribute, attribute.GetType())
                    || IsNextElement(memberAttrib, attribute, typeof(ElementAttribute)) )
                    break; // next attributes are 'elements' of the same level OR for 'sub-elements'
                else
                {
                    if( memberAttrib is MapAttribute )
                        break; // Following attributes are for this Map
                    if( memberAttrib is ElementAttribute )
                        WriteElement(writer, member, memberAttrib as ElementAttribute, attribute, mappedClass);
                }
            }
            WriteUserDefinedContent(writer, member, typeof(ElementAttribute), attribute);
            // Element: <one-to-many>
            for(; i<memberAttribs.Count; i++)
            {
                BaseAttribute memberAttrib = memberAttribs[i] as BaseAttribute;
                if( IsNextElement(memberAttrib, parentAttribute, attribute.GetType())
                    || IsNextElement(memberAttrib, attribute, typeof(OneToManyAttribute)) )
                    break; // next attributes are 'elements' of the same level OR for 'sub-elements'
                else
                {
                    if( memberAttrib is MapAttribute )
                        break; // Following attributes are for this Map
                    if( memberAttrib is OneToManyAttribute )
                        WriteOneToMany(writer, member, memberAttrib as OneToManyAttribute, attribute, mappedClass);
                }
            }
            WriteUserDefinedContent(writer, member, typeof(OneToManyAttribute), attribute);
            // Element: <many-to-many>
            for(; i<memberAttribs.Count; i++)
            {
                BaseAttribute memberAttrib = memberAttribs[i] as BaseAttribute;
                if( IsNextElement(memberAttrib, parentAttribute, attribute.GetType())
                    || IsNextElement(memberAttrib, attribute, typeof(ManyToManyAttribute)) )
                    break; // next attributes are 'elements' of the same level OR for 'sub-elements'
                else
                {
                    if( memberAttrib is MapAttribute )
                        break; // Following attributes are for this Map
                    if( memberAttrib is ManyToManyAttribute )
                        WriteManyToMany(writer, member, memberAttrib as ManyToManyAttribute, attribute, mappedClass);
                }
            }
            WriteUserDefinedContent(writer, member, typeof(ManyToManyAttribute), attribute);
            // Element: <composite-element>
            for(; i<memberAttribs.Count; i++)
            {
                BaseAttribute memberAttrib = memberAttribs[i] as BaseAttribute;
                if( IsNextElement(memberAttrib, parentAttribute, attribute.GetType())
                    || IsNextElement(memberAttrib, attribute, typeof(CompositeElementAttribute)) )
                    break; // next attributes are 'elements' of the same level OR for 'sub-elements'
                else
                {
                    if( memberAttrib is MapAttribute )
                        break; // Following attributes are for this Map
                    if( memberAttrib is CompositeElementAttribute )
                        WriteCompositeElement(writer, member, memberAttrib as CompositeElementAttribute, attribute, mappedClass);
                }
            }
            WriteUserDefinedContent(writer, member, typeof(CompositeElementAttribute), attribute);
            // Element: <many-to-any>
            for(; i<memberAttribs.Count; i++)
            {
                BaseAttribute memberAttrib = memberAttribs[i] as BaseAttribute;
                if( IsNextElement(memberAttrib, parentAttribute, attribute.GetType())
                    || IsNextElement(memberAttrib, attribute, typeof(ManyToAnyAttribute)) )
                    break; // next attributes are 'elements' of the same level OR for 'sub-elements'
                else
                {
                    if( memberAttrib is MapAttribute )
                        break; // Following attributes are for this Map
                    if( memberAttrib is ManyToAnyAttribute )
                        WriteManyToAny(writer, member, memberAttrib as ManyToAnyAttribute, attribute, mappedClass);
                }
            }
            WriteUserDefinedContent(writer, member, typeof(ManyToAnyAttribute), attribute);
            // Element: <loader>
            for(; i<memberAttribs.Count; i++)
            {
                BaseAttribute memberAttrib = memberAttribs[i] as BaseAttribute;
                if( IsNextElement(memberAttrib, parentAttribute, attribute.GetType())
                    || IsNextElement(memberAttrib, attribute, typeof(LoaderAttribute)) )
                    break; // next attributes are 'elements' of the same level OR for 'sub-elements'
                else
                {
                    if( memberAttrib is MapAttribute )
                        break; // Following attributes are for this Map
                    if( memberAttrib is LoaderAttribute )
                        WriteLoader(writer, member, memberAttrib as LoaderAttribute, attribute, mappedClass);
                }
            }
            WriteUserDefinedContent(writer, member, typeof(LoaderAttribute), attribute);
            // Element: <sql-insert>
            for(; i<memberAttribs.Count; i++)
            {
                BaseAttribute memberAttrib = memberAttribs[i] as BaseAttribute;
                if( IsNextElement(memberAttrib, parentAttribute, attribute.GetType())
                    || IsNextElement(memberAttrib, attribute, typeof(SqlInsertAttribute)) )
                    break; // next attributes are 'elements' of the same level OR for 'sub-elements'
                else
                {
                    if( memberAttrib is MapAttribute )
                        break; // Following attributes are for this Map
                    if( memberAttrib is SqlInsertAttribute )
                        WriteSqlInsert(writer, member, memberAttrib as SqlInsertAttribute, attribute, mappedClass);
                }
            }
            WriteUserDefinedContent(writer, member, typeof(SqlInsertAttribute), attribute);
            // Element: <sql-update>
            for(; i<memberAttribs.Count; i++)
            {
                BaseAttribute memberAttrib = memberAttribs[i] as BaseAttribute;
                if( IsNextElement(memberAttrib, parentAttribute, attribute.GetType())
                    || IsNextElement(memberAttrib, attribute, typeof(SqlUpdateAttribute)) )
                    break; // next attributes are 'elements' of the same level OR for 'sub-elements'
                else
                {
                    if( memberAttrib is MapAttribute )
                        break; // Following attributes are for this Map
                    if( memberAttrib is SqlUpdateAttribute )
                        WriteSqlUpdate(writer, member, memberAttrib as SqlUpdateAttribute, attribute, mappedClass);
                }
            }
            WriteUserDefinedContent(writer, member, typeof(SqlUpdateAttribute), attribute);
            // Element: <sql-delete>
            for(; i<memberAttribs.Count; i++)
            {
                BaseAttribute memberAttrib = memberAttribs[i] as BaseAttribute;
                if( IsNextElement(memberAttrib, parentAttribute, attribute.GetType())
                    || IsNextElement(memberAttrib, attribute, typeof(SqlDeleteAttribute)) )
                    break; // next attributes are 'elements' of the same level OR for 'sub-elements'
                else
                {
                    if( memberAttrib is MapAttribute )
                        break; // Following attributes are for this Map
                    if( memberAttrib is SqlDeleteAttribute )
                        WriteSqlDelete(writer, member, memberAttrib as SqlDeleteAttribute, attribute, mappedClass);
                }
            }
            WriteUserDefinedContent(writer, member, typeof(SqlDeleteAttribute), attribute);
            // Element: <sql-delete-all>
            for(; i<memberAttribs.Count; i++)
            {
                BaseAttribute memberAttrib = memberAttribs[i] as BaseAttribute;
                if( IsNextElement(memberAttrib, parentAttribute, attribute.GetType())
                    || IsNextElement(memberAttrib, attribute, typeof(SqlDeleteAllAttribute)) )
                    break; // next attributes are 'elements' of the same level OR for 'sub-elements'
                else
                {
                    if( memberAttrib is MapAttribute )
                        break; // Following attributes are for this Map
                    if( memberAttrib is SqlDeleteAllAttribute )
                        WriteSqlDeleteAll(writer, member, memberAttrib as SqlDeleteAllAttribute, attribute, mappedClass);
                }
            }
            WriteUserDefinedContent(writer, member, typeof(SqlDeleteAllAttribute), attribute);
            // Element: <filter>
            for(; i<memberAttribs.Count; i++)
            {
                BaseAttribute memberAttrib = memberAttribs[i] as BaseAttribute;
                if( IsNextElement(memberAttrib, parentAttribute, attribute.GetType())
                    || IsNextElement(memberAttrib, attribute, typeof(FilterAttribute)) )
                    break; // next attributes are 'elements' of the same level OR for 'sub-elements'
                else
                {
                    if( memberAttrib is MapAttribute )
                        break; // Following attributes are for this Map
                    if( memberAttrib is FilterAttribute )
                        WriteFilter(writer, member, memberAttrib as FilterAttribute, attribute, mappedClass);
                }
            }
            WriteUserDefinedContent(writer, member, typeof(FilterAttribute), attribute);

            writer.WriteEndElement();
        }
예제 #19
0
        public object Run(RuleContext context, object request)
        {
            #region Validations

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

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

            #endregion


            /*
             *
             */
            MemoryStream ms = new MemoryStream();
            ms.Write(context.Content.Bytes, 0, context.Content.Bytes.Length);


            /*
             *
             */
            IRule  rule     = context.Rule;
            object response = Activator.CreateInstance(rule.ResponseType);

            using (var xls = new Spreadsheet())
            {
                /*
                 * One would think that .Load would throw an error if the file isn't a
                 * valid Excel file -- but it seems to be apparently very resilient! :P
                 */
                xls.Load(ms);
                xls.AutoCalculate = false;


                /*
                 * Input
                 */
                foreach (PropertyInfo prop in request.GetType().GetProperties())
                {
                    MapAttribute map = prop.GetCustomAttribute <MapAttribute>();

                    if (map == null)
                    {
                        throw new ExcelEngineException(ER.InputMapMissing, rule.Name, prop.Name);
                    }

                    if (map.Expression == null)
                    {
                        throw new ExcelEngineException(ER.InputExpressionNull, rule.Name, prop.Name);
                    }

                    object value = prop.GetValue(request);

                    if (xls.HasCell(map.Expression) == false)
                    {
                        throw new ExcelEngineException(ER.InputCellMissing, rule.Name, prop.Name, map.Expression);
                    }

                    xls.SetValue(map.Expression, value);
                }


                /*
                 *
                 */
                xls.Calculate();


                /*
                 * Output
                 */
                foreach (PropertyInfo prop in rule.ResponseType.GetProperties())
                {
                    MapAttribute map = prop.GetCustomAttribute <MapAttribute>();

                    if (map == null)
                    {
                        throw new ExcelEngineException(ER.OutputMapMissing, rule.Name, prop.Name);
                    }

                    if (map.Expression == null)
                    {
                        throw new ExcelEngineException(ER.OutputExpressionNull, rule.Name, prop.Name);
                    }

                    if (xls.HasCell(map.Expression) == false)
                    {
                        throw new ExcelEngineException(ER.OutputCellMissing, rule.Name, prop.Name, map.Expression);
                    }

                    object value = xls.GetValue(prop.PropertyType, map.Expression);
                    prop.SetValue(response, value);
                }
            }

            return(response);
        }
예제 #20
0
        public void PlaceAttribute(MapBase tmpMap, int x, int y)
        {
            if (rbBlocked.Checked)
            {
                tmpMap.Attributes[x, y] = MapAttribute.CreateAttribute(MapAttributes.Blocked);
            }
            else if (rbItem.Checked)
            {
                tmpMap.Attributes[x, y] = MapAttribute.CreateAttribute(MapAttributes.Item);
                ((MapItemAttribute)tmpMap.Attributes[x, y]).ItemId =
                    ItemBase.IdFromList(cmbItemAttribute.SelectedIndex);

                ((MapItemAttribute)tmpMap.Attributes[x, y]).Quantity = (int)nudItemQuantity.Value;
            }
            else if (rbZDimension.Checked)
            {
                tmpMap.Attributes[x, y] = MapAttribute.CreateAttribute(MapAttributes.ZDimension);
                ((MapZDimensionAttribute)tmpMap.Attributes[x, y]).GatewayTo    = GetEditorDimensionGateway();
                ((MapZDimensionAttribute)tmpMap.Attributes[x, y]).BlockedLevel = GetEditorDimensionBlock();
            }
            else if (rbNPCAvoid.Checked)
            {
                tmpMap.Attributes[x, y] = MapAttribute.CreateAttribute(MapAttributes.NpcAvoid);
            }
            else if (rbWarp.Checked)
            {
                tmpMap.Attributes[x, y] = MapAttribute.CreateAttribute(MapAttributes.Warp);
                ((MapWarpAttribute)tmpMap.Attributes[x, y]).MapId =
                    MapList.OrderedMaps[cmbWarpMap.SelectedIndex].MapId;

                ((MapWarpAttribute)tmpMap.Attributes[x, y]).X         = (byte)nudWarpX.Value;
                ((MapWarpAttribute)tmpMap.Attributes[x, y]).Y         = (byte)nudWarpY.Value;
                ((MapWarpAttribute)tmpMap.Attributes[x, y]).Direction = (WarpDirection)cmbDirection.SelectedIndex;
            }
            else if (rbSound.Checked)
            {
                tmpMap.Attributes[x, y] = MapAttribute.CreateAttribute(MapAttributes.Sound);
                ((MapSoundAttribute)tmpMap.Attributes[x, y]).Distance = (byte)nudSoundDistance.Value;
                ((MapSoundAttribute)tmpMap.Attributes[x, y]).File     = TextUtils.SanitizeNone(cmbMapAttributeSound.Text);
            }
            else if (rbResource.Checked)
            {
                tmpMap.Attributes[x, y] = MapAttribute.CreateAttribute(MapAttributes.Resource);
                ((MapResourceAttribute)tmpMap.Attributes[x, y]).ResourceId =
                    ResourceBase.IdFromList(cmbResourceAttribute.SelectedIndex);

                if (rbLevel1.Checked)
                {
                    ((MapResourceAttribute)tmpMap.Attributes[x, y]).SpawnLevel = 0;
                }
                else
                {
                    ((MapResourceAttribute)tmpMap.Attributes[x, y]).SpawnLevel = 1;
                }
            }
            else if (rbAnimation.Checked)
            {
                tmpMap.Attributes[x, y] = MapAttribute.CreateAttribute(MapAttributes.Animation);
                ((MapAnimationAttribute)tmpMap.Attributes[x, y]).AnimationId =
                    AnimationBase.IdFromList(cmbAnimationAttribute.SelectedIndex);
            }
            else if (rbGrappleStone.Checked)
            {
                tmpMap.Attributes[x, y] = MapAttribute.CreateAttribute(MapAttributes.GrappleStone);
            }
            else if (rbSlide.Checked)
            {
                tmpMap.Attributes[x, y] = MapAttribute.CreateAttribute(MapAttributes.Slide);
                ((MapSlideAttribute)tmpMap.Attributes[x, y]).Direction = (byte)cmbSlideDir.SelectedIndex;
            }
        }
예제 #21
0
        private static MemberMappingDescriptor CreateMemberMapping(ClassMappingDescriptor classDesc, MemberInfo member)
        {
            MemberMappingDescriptor desc = new MemberMappingDescriptor();

            object[]     attrs = member.GetCustomAttributes(typeof(MapAttribute), false);
            MapAttribute attr  = (MapAttribute)attrs[0];             // todo: assert (should be exactly 1) + test

            desc.Member     = member.Name;
            desc.Expression = attr.Expression ?? "$" + desc.Member;
            if (attr.NullValue is string)
            {
                desc.NullValue = "\"" + attr.NullValue.ToString().Trim('"') + "\"";
            }
            else if (attr.NullValue != null)
            {
                desc.NullValue = attr.NullValue.ToString();
            }
            else
            {
                desc.NullValue = null;
            }
            desc.Format    = attr.Format;
            desc.OwnerType = classDesc.TargetType;

            if (member.MemberType == MemberTypes.Property)
            {
                PropertyInfo p = (PropertyInfo)member;
                desc.Type = p.PropertyType;
            }
            else
            {
                FieldInfo f = (FieldInfo)member;
                desc.Type = f.FieldType;
            }

            if (desc.HasFormatting && desc.Type != typeof(string))
            {
                string msg = string.Format(Errors.FormattingAppliedOnNonStringMember,
                                           TypeHelper.GetTypeDefinition(classDesc.TargetType),
                                           desc.Member,
                                           TypeHelper.GetTypeDefinition(desc.Type));
                throw new OtisException(msg);
            }

            if (desc.Type.IsArray)
            {
                desc.IsArray = true;
            }
            else if (typeof(ICollection).IsAssignableFrom(desc.Type) ||
                     desc.Type.GetInterface(typeof(ICollection <>).FullName) != null)
            {
                desc.IsList = true;
            }

            if (attr.HasProjection)
            {
                desc.Projections = GetProjections(desc, attr.Projection);
            }

            return(desc);
        }
예제 #22
0
        /// <summary>
        ///     Parses the tiles.
        /// </summary>
        /// <param name="node">The node.</param>
        /// <param name="tiles">The tiles.</param>
        /// <returns>Whether the tiles are parsed successfully.</returns>
        /// <exception cref="FileFormatException"></exception>
        /// <exception cref="ArgumentOutOfRangeException"></exception>
        private bool ParseTiles(Node node, out IDictionary <IVector3, ITile> tiles)
        {
            if (!ReadProperty(node, out MapStreamReader propertyReader))
            {
                throw new FileFormatException("Could not parse tile area properties.");
            }

            Vector3 basePosition = propertyReader.ReadVector3();

            tiles = new Dictionary <IVector3, ITile>();

            Node childNode = node.Child;

            while (childNode != null)
            {
                if (childNode.Type != (long)MapNodeType.Tile && childNode.Type != (long)MapNodeType.HouseTile)
                {
                    throw new FileFormatException("Could not find tile node.");
                }
                if (!ReadProperty(childNode, out propertyReader))
                {
                    throw new FileFormatException("Could not parse tile vector2 properties.");
                }

                Vector2 positionOffset = propertyReader.ReadVector2();
                Vector3 tilePosition   = new Vector3(basePosition.X + positionOffset.X, basePosition.Y + positionOffset.Y, basePosition.Z);
                if (!tiles.ContainsKey(tilePosition))
                {
                    Tile tile = new Tile
                    {
                        Position = tilePosition
                    };
                    tiles.Add(tile.Position, tile);

                    if (childNode.Type == (long)MapNodeType.HouseTile)
                    {
                        uint houseId = propertyReader.ReadUInt32();
                        if (houseId == 0)
                        {
                            throw new FileFormatException($"Invalid house ID at position [x: {tile.Position.X}, y: {tile.Position.Y}, z: {tile.Position.Z}].");
                        }

                        tile.HouseId = houseId;
                    }

                    // Tile attributes
                    while (propertyReader.PeekChar() != -1)
                    {
                        MapAttribute attribute = (MapAttribute)propertyReader.ReadByte();
                        switch (attribute)
                        {
                        case MapAttribute.TileFlags:
                            uint flags = propertyReader.ReadUInt32();
                            if (flags == 0)
                            {
                                throw new FileFormatException("Invalid tile flags.");
                            }
                            tile.Flags = (TileFlags)flags;
                            break;

                        case MapAttribute.TileItem:
                            ushort itemId = propertyReader.ReadUInt16();
                            if (itemId == 0)
                            {
                                throw new FileFormatException($"Invalid item ID at position [x: {tile.Position.X}, y: {tile.Position.Y}, z: {tile.Position.Z}].");
                            }

                            AddTileItem(tile, itemId);
                            break;

                        default:
                            throw new ArgumentOutOfRangeException(nameof(attribute), attribute, "OTBM attribute is not supported.");
                        }
                    }

                    // Tile items
                    Node nodeItem = childNode.Child;
                    while (nodeItem != null)
                    {
                        if (nodeItem.Type != (long)MapNodeType.Item)
                        {
                            throw new FileFormatException("Could not find item node.");
                        }
                        if (!ReadProperty(nodeItem, out propertyReader))
                        {
                            throw new FileFormatException("Could not parse item properties.");
                        }

                        ushort itemId = propertyReader.ReadUInt16();
                        if (itemId == 0)
                        {
                            throw new FileFormatException($"Invalid item ID at position [x: {tile.Position.X}, y: {tile.Position.Y}, z: {tile.Position.Z}].");
                        }

                        AddTileItem(tile, itemId);
                        nodeItem = nodeItem.Next;
                    }
                }

                childNode = childNode.Next;
            }
            return(true);
        }
예제 #23
0
        /// <summary>
        ///     Loads the specified file name.
        /// </summary>
        /// <param name="fileName">Name of the file.</param>
        /// <returns>The map.</returns>
        /// <exception cref="FileFormatException"></exception>
        /// <exception cref="ArgumentOutOfRangeException"></exception>
        private WorldMap Load(string fileName)
        {
            string workingFolder = Path.GetDirectoryName(fileName);

            OpenFile(fileName);

            // File version
            Reader.ReadUInt32();

            // Initialize
            InitializeRoot();

            if (Reader.ReadByte() != NodeTags.StartTag)
            {
                throw new FileFormatException("Could not find start node.");
            }

            //if (!ParseNode(Root))
            //    throw new FileFormatException("Could not parse root node.");
            // TODO: This should probably throw an exception if the return is 'false'(?)
            ParseNode(Root);

            Node node = GetRootNode();

            if (!ReadProperty(node, out MapStreamReader mapPropertyReader))
            {
                throw new FileFormatException("Could not parse root node properties.");
            }

            // First byte of OTB is 0
            // TODO: Use propertyReader.Skip(byte.size); - byte.size is unknown
            mapPropertyReader.ReadByte();
            MapMetadata metadata = mapPropertyReader.ReadMetadata();

            if (metadata == null)
            {
                throw new FileFormatException("Could not read OTBM metadata.");
            }

            WorldMap map = new WorldMap
            {
                Width  = metadata.Width,
                Height = metadata.Height
            };

            node = node.Child;
            if ((MapNodeType)node.Type != MapNodeType.MapData)
            {
                throw new FileFormatException("Could not find map data node.");
            }
            if (!ReadProperty(node, out mapPropertyReader))
            {
                throw new FileFormatException("Could not parse OTBM attribute.");
            }

            while (mapPropertyReader.PeekChar() != -1)
            {
                MapAttribute attribute = (MapAttribute)mapPropertyReader.ReadByte();
                switch (attribute)
                {
                case MapAttribute.Description:
                    map.Description = mapPropertyReader.ReadString();
                    break;

                case MapAttribute.ExtSpawnFile:
                    string spawnFile = mapPropertyReader.ReadString();
                    map.SpawnFile = Path.Combine(workingFolder, spawnFile);
                    break;

                case MapAttribute.ExtHouseFile:
                    string houseFile = mapPropertyReader.ReadString();
                    map.HouseFile = Path.Combine(workingFolder, houseFile);
                    break;

                default:
                    throw new ArgumentException($"OTBM attribute '{attribute}' is not supported.");
                }
            }

            Node childNode = node.Child;

            while (childNode != null)
            {
                MapNodeType nodeType = (MapNodeType)childNode.Type;
                switch (nodeType)
                {
                case MapNodeType.Tiles:
                    if (!ParseTiles(childNode, out IDictionary <IVector3, ITile> tiles))
                    {
                        throw new FileFormatException("Could not parse tiles.");
                    }
                    map.Tiles.AddRange(tiles);
                    break;

                case MapNodeType.Towns:
                    if (!TryParseTowns(childNode, out IDictionary <uint, ITown> towns))
                    {
                        throw new FileFormatException("Could not parse towns.");
                    }
                    map.Towns.AddRange(towns);
                    break;

                case MapNodeType.Waypoints:
                    if (!TryParseWaypoints(childNode, out IDictionary <string, IWaypoint> waypoints))
                    {
                        throw new FileFormatException("Could not parse waypoints.");
                    }
                    map.Waypoints.AddRange(waypoints);
                    break;

                default:
                    throw new ArgumentOutOfRangeException(nameof(nodeType), nodeType, "OTBM node type is not supported.");
                }

                childNode = childNode.Next;
            }

            return(map);
        }
        public MapAttribute CreateAttribute()
        {
            var attributeType = SelectedMapAttributeType;
            var attribute     = MapAttribute.CreateAttribute(attributeType);

            switch (SelectedMapAttributeType)
            {
            case MapAttributes.Walkable:
            case MapAttributes.Blocked:
            case MapAttributes.GrappleStone:
            case MapAttributes.NpcAvoid:
                break;

            case MapAttributes.Item:
                var itemAttribute = attribute as MapItemAttribute;
                itemAttribute.ItemId   = ItemBase.IdFromList(cmbItemAttribute.SelectedIndex);
                itemAttribute.Quantity = (int)nudItemQuantity.Value;
                break;

            case MapAttributes.ZDimension:
                var zDimensionAttribute = attribute as MapZDimensionAttribute;
                zDimensionAttribute.GatewayTo    = GetEditorDimensionGateway();
                zDimensionAttribute.BlockedLevel = GetEditorDimensionBlock();
                break;

            case MapAttributes.Warp:
                var warpAttribute = attribute as MapWarpAttribute;
                warpAttribute.MapId     = MapList.OrderedMaps[cmbWarpMap.SelectedIndex].MapId;
                warpAttribute.X         = (byte)nudWarpX.Value;
                warpAttribute.Y         = (byte)nudWarpY.Value;
                warpAttribute.Direction = (WarpDirection)cmbDirection.SelectedIndex;
                break;

            case MapAttributes.Sound:
                var soundAttribute = attribute as MapSoundAttribute;
                soundAttribute.Distance     = (byte)nudSoundDistance.Value;
                soundAttribute.File         = TextUtils.SanitizeNone(cmbMapAttributeSound.Text);
                soundAttribute.LoopInterval = (int)nudSoundLoopInterval.Value;
                break;

            case MapAttributes.Resource:
                var resourceAttribute = attribute as MapResourceAttribute;
                resourceAttribute.ResourceId = ResourceBase.IdFromList(cmbResourceAttribute.SelectedIndex);
                resourceAttribute.SpawnLevel = (byte)(rbLevel1.Checked ? 0 : 1);
                break;

            case MapAttributes.Animation:
                var animationAttribute = attribute as MapAnimationAttribute;
                animationAttribute.AnimationId = AnimationBase.IdFromList(cmbAnimationAttribute.SelectedIndex);
                break;

            case MapAttributes.Slide:
                var slideAttribute = attribute as MapSlideAttribute;
                slideAttribute.Direction = (byte)cmbSlideDir.SelectedIndex;
                break;

            default:
                throw new ArgumentOutOfRangeException(nameof(SelectedMapAttributeType), @"The currently selected attribute type has not been fully implemented.");
            }

            return(attribute);
        }
예제 #25
0
        /// <summary>
        /// <para>This method generates a unique id (always positive but unique amongst both
        /// negative and positive ids) for the specific type and within the specific mapdata context.</para>
        /// <para>Currently the following types are distinctly supported:</para>
        /// <li>Astraea.Inframap.Layout.Data.MapNode</li>
        /// <li>Astraea.Inframap.Layout.Data.MapLink</li>
        /// <li>Astraea.Inframap.Layout.Data.Map.Port</li>
        /// </summary>
        /// <param name="entityType">this is the type of entity that we generate the id for.</param>
        /// <param name="mapdata">this is the context for which the id must be unique</param>
        /// <returns>the generated unique id</returns>
        /// <exception cref="SelfDocumentingException">
        /// Wraps ArgumentNullException if entityType or mapdata is null.
        /// Wraps ArgumentException if entityType is not a supported type.
        /// </exception>
        protected virtual long GenerateUniqueId(Type entityType, MapData mapdata)
        {
            Helper.Log(logger, Level.INFO,
                       "Entering GenerateUniqueId with entityType: {0} mapdata {1}.",
                       new object[] { entityType, mapdata });

            long maxId = 0;

            try
            {
                //Validate
                Helper.ValidateNotNull(entityType, "entityType");
                Helper.ValidateNotNull(mapdata, "mapdata");
                if (entityType != typeof(MapNode) &&
                    entityType != typeof(MapLink) &&
                    entityType != typeof(MapPort) &&
                    entityType != typeof(MapAttribute))
                {
                    throw new ArgumentException(
                              "Unique ids are supported only for types MapNode, MapLink and MapPort.", "entityType");
                }

                //Get the appropriate list from the MapData
                IEnumerator typeListEn = null;
                if (entityType.Equals(typeof(MapNode)))
                {
                    typeListEn = mapdata.Nodes.GetEnumerator();
                }
                else if (entityType.Equals(typeof(MapLink)))
                {
                    typeListEn = mapdata.Links.GetEnumerator();
                }
                else if (entityType.Equals(typeof(MapPort)))
                {
                    typeListEn = mapdata.Ports.GetEnumerator();
                }
                else if (entityType.Equals(typeof(MapAttribute)))
                {
                    typeListEn = mapdata.Attributes.GetEnumerator();
                }

                if (entityType.Equals(typeof(MapAttribute)))
                {
                    //Get the maximum id of the attributes in the list.
                    while (typeListEn.MoveNext())
                    {
                        MapAttribute mapAttribute = (MapAttribute)typeListEn.Current;
                        maxId = Math.Max(maxId, Math.Abs(mapAttribute.Id));
                    }
                }
                else
                {
                    //Get the maximum id of the elements in the list.
                    while (typeListEn.MoveNext())
                    {
                        MapElement mapElement = (MapElement)typeListEn.Current;
                        maxId = Math.Max(maxId, Math.Abs(mapElement.Id));
                    }
                }

                return(maxId + 1);
            }
            catch (Exception e)
            {
                Helper.Log(logger, Level.ERROR,
                           "Error in GenerateUniqueId with error: {0}.", new object[] { e.Message });

                throw Helper.GetSelfDocumentingException(e, "Unable to generate unique id.",
                                                         "Astraea.Inframap.Layout.BaseLayoutEngine.GenerateUniqueId",
                                                         new string[] { "config", "graphLayouter", "logger" },
                                                         new object[] { config, graphLayouter, logger },
                                                         new string[] { "entityType", "mapdata" }, new object[] { entityType, mapdata },
                                                         new string[0], new object[0]);
            }
            finally
            {
                Helper.Log(logger, Level.INFO,
                           "Exiting GenerateUniqueId with return value: {0}.", new object[] { maxId + 1 });
            }
        }
예제 #26
0
        /// <summary>
        /// This method performs the following logic:
        /// For each link in the mapdata, it gets the nodes defining the link from its 'path' attributes.
        /// For each such node, it creates a new synthetic node as a child of the node.
        /// For each such synthetic node, it creates a port for it.
        /// It then forms new links between the nodes of the original link and the new ports formed.
        /// Finally it adds all the new links formed to the mapdata and removes the original link.
        /// </summary>
        /// <param name="mapdata">MapData to be processed</param>
        private void AddNewLinksAndSyntheticNodes(MapData mapdata)
        {
            IList <MapLink> linksToDelete = new List <MapLink>();
            IList <MapLink> linksToAdd    = new List <MapLink>();

            foreach (ILink link in mapdata.Links)
            {
                MapLink mapLink = (MapLink)link;

                //Get the path attributes
                IList <IAttribute> pathAttrs = mapLink.GetAttributesByName(Path);

                //Preserve the original link if no path attributes are found
                if (pathAttrs == null || pathAttrs.Count == 0)
                {
                    continue;
                }

                //Get the nodes of the path
                IList <MapNode> pathNodes = new List <MapNode>();
                foreach (IAttribute attr in pathAttrs)
                {
                    MapAttribute pathAttr = (MapAttribute)attr;
                    if (pathAttr.Type.Equals(AttrTypeInt))
                    {
                        pathNodes.Add((MapNode)mapdata.GetNodeById(pathAttr.IntValue));
                    }
                    else if (pathAttr.Type.Equals(AttrTypeString))
                    {
                        pathNodes.Add((MapNode)mapdata.GetNodeByName(pathAttr.StringValue));
                    }
                }

                //Create the synthetic nodes for each path node.
                IList <MapNode> syntheticNodes = new List <MapNode>();
                foreach (MapNode pathNode in pathNodes)
                {
                    if (mapdata.Nodes.Contains(pathNode))
                    {
                        //Get the unique id for the new synthetic node and set it
                        long    syntheticNodeId = GetUniqueId(typeof(MapNode), mapdata, 0);
                        MapNode syntheticNode   = new MapNode();
                        syntheticNode.Id   = syntheticNodeId;
                        syntheticNode.Name = MapNodeNamePrefix + syntheticNodeId;

                        //Add it as child node of pathNode
                        pathNode.AddOccupant(syntheticNode);
                        syntheticNode.Container = pathNode;

                        //Add it to the mapData
                        mapdata.AddNode(syntheticNode);

                        //Create and add port to synthetic node.
                        long    syntheticNodePortId = GetUniqueId(typeof(MapPort), mapdata, 0);
                        MapPort syntheticNodePort   = new MapPort();
                        syntheticNodePort.Id   = syntheticNodePortId;
                        syntheticNodePort.Name = MapPortNamePrefix + syntheticNodePortId;
                        syntheticNode.AddPort(syntheticNodePort);

                        //Add synthetic node to the port
                        syntheticNodePort.Node = syntheticNode;

                        //Add created port to the mapdata
                        mapdata.AddPort(syntheticNodePort);

                        //Save it further processing
                        syntheticNodes.Add(syntheticNode);
                    }
                }

                //None of the path nodes were found in the mapdata nodes.
                if (syntheticNodes.Count == 0)
                {
                    continue;
                }

                //Create new links
                //1)Note that we first get port and then get the node from the port.
                //See http://forums.topcoder.com/?module=Thread&threadID=592050&start=0&mc=24#885358
                //2)Links are guaranteed to have exactly 2 nodes
                MapPort startPort = (MapPort)mapLink.Ports[0];
                MapNode startNode = (MapNode)startPort.Node;
                MapNode endNode   = null;
                MapPort endPort   = null;
                for (int i = 0; i < syntheticNodes.Count; i++)
                {
                    endNode = syntheticNodes[i];
                    endPort = (MapPort)syntheticNodes[i].Ports[0];

                    //Create link and save it for adding later
                    linksToAdd.Add(CreateNewLink(startNode, endNode, startPort, endPort, mapdata, mapLink, linksToAdd.Count));

                    startNode = endNode;
                    startPort = endPort;
                }
                endPort = (MapPort)mapLink.Ports[1];
                endNode = (MapNode)endPort.Node;
                //Create last link and save it for adding later
                linksToAdd.Add(CreateNewLink(startNode, endNode, startPort, endPort, mapdata, mapLink, linksToAdd.Count));

                //Save original link for deleting it later
                linksToDelete.Add(mapLink);
            }

            //Remove the original links
            foreach (MapLink linkToDelete in linksToDelete)
            {
                //Remove link's attributes from mapdata
                foreach (IAttribute linkAttr in linkToDelete.Attributes)
                {
                    mapdata.RemoveAttribute((MapAttribute)linkAttr);
                }
                //REmove the link itself from mapdata
                mapdata.RemoveLink(linkToDelete);
            }

            //Add the new links
            foreach (MapLink linkToAdd in linksToAdd)
            {
                mapdata.AddLink(linkToAdd);
            }
        }
예제 #27
0
        /// <summary>
        /// Creates a sample Map Data for the tests.
        /// </summary>
        /// <returns>A sample MapData instance</returns>
        internal static MapData GetSampleMapData()
        {
            MapData md = new MapData();

            //Create some nodes and add them to the mapdata
            MapNode nodeA = new MapNode();

            SetMockIdAndName(nodeA, 123, "nodeA");
            AddMockPort(nodeA, null);

            MapNode nodeB = new MapNode();

            SetMockIdAndName(nodeB, 234, "nodeB");
            AddMockPort(nodeB, null);

            MapNode nodeC = new MapNode();

            SetMockIdAndName(nodeC, 012, "nodeC");

            MapNode nodeX = new MapNode();

            SetMockIdAndName(nodeX, 666, "nodeX");
            AddMockPort(nodeX, null);

            MapNode nodeY = new MapNode();

            SetMockIdAndName(nodeY, 667, "nodeY");
            AddMockPort(nodeY, null);

            MapNode nodeZ = new MapNode();

            SetMockIdAndName(nodeZ, 668, "nodeZ");
            AddMockPort(nodeZ, null);

            md.Nodes.Add(nodeA);
            md.Nodes.Add(nodeB);
            md.Nodes.Add(nodeX);
            md.Nodes.Add(nodeY);
            md.Nodes.Add(nodeZ);

            //Create a link (from A to B) and add it to the mapData
            MapLink linkA = new MapLink();

            SetMockIdAndName(linkA, 1001, "linkA");
            linkA.AddNode(nodeA);
            linkA.AddNode(nodeB);
            //Note ports do not have to be in the same order as the links
            linkA.AddPort((MapPort)nodeB.Ports[0]);
            linkA.AddPort((MapPort)nodeA.Ports[0]);

            //Create a link (from B to C) and add it to the mapData
            MapLink linkB = new MapLink();

            SetMockIdAndName(linkB, 1000, "linkB");
            linkA.AddNode(nodeB);
            linkA.AddNode(nodeC);

            md.Links.Add(linkA);
            md.Links.Add(linkB);

            //Create a linked port
            nodeB.Ports[0].Links.Add(linkA);

            //Set header
            md.Header = new MapHeader();

            //Create linkedport for NodeC
            AddMockPort(nodeC, linkB);


            //path with 3 nodes for LinkA
            MapAttribute ma1 = new MapAttribute();

            ma1.IntValue = 666;
            ma1.Type     = "int";
            ma1.Name     = "path";
            MapAttribute ma2 = new MapAttribute();

            ma2.IntValue = 667;
            ma2.Type     = "int";
            ma2.Name     = "path";
            MapAttribute ma3 = new MapAttribute();

            ma3.StringValue = "nodeZ";
            ma3.Type        = "string";
            ma3.Name        = "path";
            linkA.AddAttribute(ma1);
            linkA.AddAttribute(ma2);
            linkA.AddAttribute(ma3);

            return(md);
        }