GetValue() private method

private GetValue ( object obj ) : object
obj object
return object
Esempio n. 1
0
        public static bool ArePropertiesEqual(PropertyInfo property, object object1, object object2)
        {
            bool result = true;

            object object1Value = null;
            object object2Value = null;

            if (object1 != null)
            {
                object1Value = property.GetValue(object1, null);
            }
            if (object2 != null)
            {
                object2Value = property.GetValue(object2, null);
            }

            if (object1Value != null)
            {
                if (object1Value.Equals(object2Value) == false)
                {
                    result = false;
                }
            }
            else
            {
                if (object2Value != null)
                {
                    result = false;
                }
            }

            return result;
        }
Esempio n. 2
0
        /// <summary>
        /// 获取对象的属性名或者描述和值的键值对列表
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj"></param>
        /// <param name="isToDesc"></param>
        /// <returns></returns>
        public static Dictionary <string, string> GetPropOrDescKeyValueDict <T>(this T obj, bool isToDesc = false) where T : class
        {
            Dictionary <string, string> dict = new Dictionary <string, string>();
            var allProoKeys = obj.GetAllPropKeys();

            foreach (var propKeyName in allProoKeys)
            {
                Type type = obj.GetType();                                            //获取类型
                Reflection.PropertyInfo propertyInfo = type.GetProperty(propKeyName); //获取指定名称的属性
                var value = propertyInfo.GetValue(obj, null).ToString();              //获取属性值

                string desc = "";

                if (isToDesc)
                {
                    object[] objs = typeof(T).GetProperty(propKeyName).GetCustomAttributes(typeof(DescriptionAttribute), true);
                    if (objs.Length > 0)
                    {
                        desc = ((DescriptionAttribute)objs[0]).Description;
                    }
                    else
                    {
                        desc = propKeyName;
                    }
                }
                else
                {
                    desc = propKeyName;
                }

                dict.Add(desc, value);
            }
            return(dict);
        }
 private static void CheckAndCopyGenericType <T>(T result, Reflection.PropertyInfo tp, object value)
 {
     if (tp.PropertyType.IsGenericType)
     {
         var lst = tp.GetValue(result, null);
         if (lst != null)
         {
             if (lst is IList)
             {
                 foreach (var item in value as IList)
                 {
                     (lst as IList).Add(item.CopyProperties(true));
                 }
             }
         }
     }
 }
Esempio n. 4
0
        public static java.lang.Class getClass(this System.Object t)
        {
            Type runtimeType = t.GetType();

            Reflection.PropertyInfo propInfo = runtimeType.GetProperty("UnderlyingSystemType");
            Type type = null == propInfo ? runtimeType : (Type)propInfo.GetValue(t, null);

            java.lang.Class clazz = null;
            if (loadedClasses.containsKey(type))
            {
                clazz = loadedClasses.get(type);
            }
            else
            {
                clazz = new java.lang.Class(type);
                loadedClasses.put(type, clazz);
            }

            return(clazz);
        }
Esempio n. 5
0
        /// <summary>
        /// Recursively prints objects property names and values, as well as child objects
        /// </summary>
        /// <param name="prop">PropertyInfo object</param>
        /// <param name="o">The object it belongs to</param>
        /// <param name="linecount">How many lines we've printed since the last "...more"</param>
        /// <param name="more">How many lines to print before stopping and writing "...more"</param>
        /// <param name="prefix">Prefix for indentation of nested properties</param>
        /// <returns>Int - the current line counter</returns>
        public static int DumpConfigObject(System.Reflection.PropertyInfo prop, Object o, int linecount, int more, string prefix = null)
        {
            //don't print empty/null properties
            if (!String.IsNullOrEmpty(Convert.ToString(prop.GetValue(o, null))))
            {
                //some nice color highlighting of the names/values just to make the output more readable
                ConsoleColor propColor  = ConsoleColor.Gray;
                ConsoleColor nameColor  = ConsoleColor.Green;
                ConsoleColor valueColor = ConsoleColor.Yellow;
                Console.ForegroundColor = propColor;

                //prefix for indenting nested properties
                if (prefix != null)
                {
                    //use Cyan for nested properties names to break up the monotony
                    nameColor = ConsoleColor.Cyan;
                    Console.Write(prefix + "Property: ");
                }
                else
                {
                    Console.Write("Property: ");
                }

                Console.ForegroundColor = nameColor;
                Console.Write(prop.Name);
                Console.ForegroundColor = propColor;
                Console.Write(" = ");
                Console.ForegroundColor = valueColor;
                //write the property's value and retrieve current line count
                linecount = WriteLine(Convert.ToString(prop.GetValue(o, null)), linecount, more);

                //get the type of the property's value
                Type type = prop.GetValue(o, null).GetType();

                //for "primitive" types (or enums, strings) we are done. for anything else they can have nested objects
                //so we go through those and recurseively print them. arrays need to be handled somewhat specially because
                //they can
                if (!(type.IsPrimitive || type.Equals(typeof(string)) || type.BaseType.Equals(typeof(Enum))))
                {
                    var getMethod = prop.GetGetMethod();
                    if (prop.GetValue(o, null) is IEnumerable)
                    {
                        prefix = ((prefix != null) ? prefix : "") + "    ";
                        IEnumerable enumerableObject = (IEnumerable)getMethod.Invoke(o, null);
                        if (enumerableObject != null)
                        {
                            foreach (object element in enumerableObject)
                            {
                                Type elemType = element.GetType();
                                //if it's an array of primitives, just print each element. otherwise we need the recursive call
                                if (elemType.IsPrimitive || elemType.Equals(typeof(string)) || elemType.BaseType.Equals(typeof(Enum)))
                                {
                                    Console.ForegroundColor = propColor;
                                    Console.Write(prefix + "Element = ");
                                    Console.ForegroundColor = valueColor;
                                    linecount = WriteLine(Convert.ToString(element), linecount, more);
                                }
                                else
                                {
                                    //recursive call for arrays of objects
                                    foreach (PropertyInfo p in element.GetType().GetProperties())
                                    {
                                        linecount = DumpConfigObject(p, element, linecount, more, prefix);
                                    }
                                }
                            }
                        }
                    }
                    else
                    {
                        //this handles other types of objects that aren't arrays such as tables.table[x].columnList
                        prefix = ((prefix != null) ? prefix : "") + "    ";
                        foreach (PropertyInfo p in prop.GetValue(o, null).GetType().GetProperties())
                        {
                            linecount = DumpConfigObject(p, prop.GetValue(o, null), linecount, more, prefix);
                        }
                    }
                }
            }
            return(linecount);
        }
Esempio n. 6
0
 /// <summary>
 /// simple property invoke
 /// </summary>
 /// <param name="obj"></param>
 /// <param name="propertyName"></param>
 /// <returns></returns>
 internal static object InvokeProperty(object obj, string propertyName)
 {
     System.Reflection.PropertyInfo p = obj.GetType().GetProperty(propertyName);
     return(p.GetValue(obj, null));
 }
Esempio n. 7
0
 public object GetPropertyValue(System.Reflection.PropertyInfo property)
 {
     return((source != null) ? property.GetValue(source, null) : null);
 }
        /// <summary>
        /// 把页面控件上的值赋值给实体对象
        /// </summary>
        /// <typeparam name="T">实体类型</typeparam>
        /// <param name="page">页面</param>
        /// <param name="type">反射类型</param>
        /// <param name="entity">返回实体类</param>
        public static void SetControlValueToEntity <T>(Page page, ref T entity)
        {
            foreach (System.Reflection.PropertyInfo pro in typeof(T).GetProperties())
            {
                try
                {
                    Control       control   = page.Form.FindControl("txt" + pro.Name);
                    Control       hiddenCtr = page.Form.FindControl("hide" + pro.Name);
                    CusControlObj em        = (CusControlObj)page.Form.FindControl(pro.Name);
                    #region 取自定义控件select的值
                    if (em != null)
                    {
                        SetEntityValue <T>(pro, ref entity, em.IdValue);
                    }
                    #endregion
                    #region hidden input
                    if (hiddenCtr != null)
                    {
                        HtmlInputHidden hInput = (HtmlInputHidden)hiddenCtr;
                        if (hInput != null)
                        {
                            SetEntityValue <T>(pro, ref entity, hInput.Value);
                        }
                    }
                    #endregion
                    #region normal control
                    if (control == null)
                    {
                        continue;
                    }

                    if (control is HtmlGenericControl)
                    {
                        HtmlGenericControl txt = (HtmlGenericControl)control;
                        SetEntityValue <T>(pro, ref entity, txt.InnerHtml);
                    }
                    if (control is HtmlInputText)
                    {
                        HtmlInputText txt = (HtmlInputText)control;
                        SetEntityValue <T>(pro, ref entity, txt.Value);
                    }
                    if (control is TextBox)
                    {
                        TextBox txt = (TextBox)control;
                        SetEntityValue <T>(pro, ref entity, txt.Text);
                    }
                    if (control is HtmlSelect)
                    {
                        HtmlSelect txt = (HtmlSelect)control;
                        SetEntityValue <T>(pro, ref entity, txt.Value);
                    }
                    if (control is HtmlInputHidden)
                    {
                        HtmlInputHidden txt = (HtmlInputHidden)control;
                        SetEntityValue <T>(pro, ref entity, txt.Value);
                    }
                    if (control is HtmlInputPassword)
                    {
                        HtmlInputPassword txt = (HtmlInputPassword)control;
                        SetEntityValue <T>(pro, ref entity, txt.Value);
                    }
                    if (control is Label)
                    {
                        Label txt = (Label)control;
                        SetEntityValue <T>(pro, ref entity, txt.Text);
                    }
                    if (control is HtmlInputCheckBox)
                    {
                        HtmlInputCheckBox chk = (HtmlInputCheckBox)control;
                        SetEntityValue <T>(pro, ref entity, chk.Checked.ToString());
                    }
                    if (control is HtmlTextArea)
                    {
                        HtmlTextArea area = (HtmlTextArea)control;
                        SetEntityValue <T>(pro, ref entity, area.Value);
                    }
                    if (control is DropDownList)
                    {
                        DropDownList drp = (DropDownList)control;
                        SetEntityValue <T>(pro, ref entity, drp.SelectedValue);
                    }
                    #region 取自定义用户控件的值
                    if (control is UserControl)
                    {
                        UserControl userControl = (UserControl)control;
                        Type        userType    = userControl.GetType();
                        System.Reflection.PropertyInfo proInfo = userType.GetProperty("Value");
                        if (proInfo != null)
                        {
                            SetEntityValue <T>(pro, ref entity, proInfo.GetValue(userControl, null).ToString());
                        }
                    }
                    #endregion
                    #endregion
                }
                catch
                {
                    throw;
                }
            }
        }
Esempio n. 9
0
    /// <summary>
    /// Searches Active Directory according provided parameters
    /// </summary>
    /// <param name="userName">UserName to be used to authenticate AD</param>
    /// <param name="password">Password to be used to authenticate to AD</param>
    /// <param name="authType">Authentication type to be used to authenticate to AD</param>
    /// <param name="adRoot">AD Root for querying AD</param>
    /// <param name="filter">Filter to be used for querying</param>
    /// <param name="searchScope">Scope to be used for queryingg</param>
    /// <param name="propertiesToLoad">List of properties to return</param>
    /// <param name="pageSize">Represents a PageSise for the paged search of AD</param>
    /// <param name="rowsLimit">Rrepresent limit for numbers of rows returned. NULL or value less than 1 represents unlimited</param>
    private static void SearchAD(string userName, string password, string authType, string adRoot, string filter, string searchScope, string propertiesToLoad, int pageSize, SqlInt32 rowsLimit)
    {
        string[]         properties     = propertiesToLoad.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
        ADPropertyInfo[] adProperties   = new ADPropertyInfo[properties.Length];
        SqlMetaData[]    recordMetaData = new SqlMetaData[properties.Length];
        SearchScope      scope;
        Type             et = typeof(Encoding); //Encoding Type

        int limit     = rowsLimit.IsNull ? 0 : rowsLimit.Value;
        int rowsCount = 0;

        if (rowsLimit > 0 && pageSize > limit)
        {
            pageSize = limit;
        }

        if (!TryParseEnum <SearchScope>(searchScope, true, out scope))
        {
            throw new System.InvalidCastException(string.Format("searchScope must be one of '{0}'", GetEnumNames <SearchScope>()));
        }


        //Trim properties and prepare result set metadata, also process specified lengths
        for (int i = 0; i < properties.Length; i++)
        {
            string[] propDetails = properties[i].Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);  //Properties detals - Split to Name, Length, Decoder and Encoder
            string   propName    = propDetails[0].Trim();
            int      len         = 4000;
            int      tmpLen;
            bool     isBinary        = false;
            Encoding decoder         = Encoding.Unicode;
            Encoding encoder         = Encoding.Unicode;
            bool     encodingBiinary = false;

            #region Field Length Retrieval

            if (propDetails.Length > 1)
            {
                //if length is "max" then set len = -1 whihc equals to MAX
                if (propDetails[1].ToLower() == "max")
                {
                    len = -1;
                }
                else if (int.TryParse(propDetails[1], out tmpLen) && tmpLen >= 1 && tmpLen <= 4000)
                {
                    len = tmpLen;
                }
                else
                {
                    throw new System.InvalidCastException(string.Format("[{0}] - Length of field has to be numeric value in range 1 - 4000 or max", properties[i]));
                }
            }

            #endregion

            #region Get Decoder and Encoder
            //find Encoding
            if (propDetails.Length >= 3)
            {
                decoder = null;
                Exception exc = null;

                //If Decoder or Encoder is BINARY then we will use a binary storage
                if (propDetails[2] == "BINARY" || (propDetails.Length >= 4 && propDetails[3] == "BINARY"))
                {
                    isBinary = true;
                }

                if (propDetails.Length >= 4 && propDetails[3] == "BINARY")
                {
                    encodingBiinary = true;
                }

                //Get Decoder
                if (propDetails[2] != "BINARY")
                {
                    int codePage;
                    try
                    {
                        if (int.TryParse(propDetails[2].Trim(), out codePage))
                        {
                            decoder = Encoding.GetEncoding(codePage);
                        }
                        else
                        {
                            //Try to get static property of the Encoding Class
                            System.Reflection.PropertyInfo pi = et.GetProperty(propDetails[2].Trim(), et);

                            //if the static property does not exists, treats the name as Code Page name
                            if (pi == null)
                            {
                                decoder = Encoding.GetEncoding(propDetails[2].Trim());
                            }
                            else if (pi.CanRead)
                            {
                                decoder = pi.GetValue(null, null) as Encoding;
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        exc = e;
                    }

                    if (decoder == null)
                    {
                        //Get List of available static properties of the EncodingClass
                        StringBuilder sb = new StringBuilder();
                        sb.Append("BINARY");

                        foreach (PropertyInfo p in et.GetProperties(BindingFlags.GetProperty | BindingFlags.Public | BindingFlags.Static))
                        {
                            if (p.PropertyType == et)
                            {
                                sb.Append(",");
                                sb.Append(p.Name);
                            }
                        }
                        throw new System.NotSupportedException(string.Format("[{0}] - Decoder has to be one of {1} or a CodePage Numer or CodePage name. For Code Pages see http://msdn.microsoft.com/en-us/library/vstudio/system.text.encoding(v=vs.100).aspx", properties[i], sb.ToString()), exc);
                    }
                }

                //Get Encoder
                if (propDetails.Length >= 4 && propDetails[3] != "BINARY")
                {
                    encoder = null;
                    int codePage;

                    try
                    {
                        //In case of CodePage number, try to get code page
                        if (int.TryParse(propDetails[3].Trim(), out codePage))
                        {
                            encoder = Encoding.GetEncoding(codePage);
                        }
                        else
                        {
                            //Try to get static property of the Encoding Class
                            System.Reflection.PropertyInfo pi = et.GetProperty(propDetails[2].Trim(), et);

                            //if the static property does not exists, treats the name as Code Page name
                            if (pi == null)
                            {
                                encoder = Encoding.GetEncoding(propDetails[2].Trim());
                            }
                            else if (pi.CanRead)
                            {
                                encoder = pi.GetValue(null, null) as Encoding;
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        exc = e;
                    }

                    if (encoder == null)
                    {
                        //Get List of available static properties of the EncodingClass
                        StringBuilder sb = new StringBuilder();
                        sb.Append("BINARY");

                        foreach (PropertyInfo p in et.GetProperties(BindingFlags.GetProperty | BindingFlags.Public | BindingFlags.Static))
                        {
                            if (p.PropertyType == et)
                            {
                                sb.Append(",");
                                sb.Append(p.Name);
                            }
                        }
                        throw new System.NotSupportedException(string.Format("[{0}] - Encoder has to be one of {1} or a CodePage Numer or CodePage name. For Code Pages see http://msdn.microsoft.com/en-us/library/vstudio/system.text.encoding(v=vs.100).aspx", properties[i], sb.ToString()), exc);
                    }
                }
            }
            #endregion

            //IF Binary, use VarBinary data type otherwise NVarChar
            if (isBinary)
            {
                recordMetaData[i] = new SqlMetaData(propName, System.Data.SqlDbType.VarBinary, len);
            }
            else
            {
                recordMetaData[i] = new SqlMetaData(propName, System.Data.SqlDbType.NVarChar, len);
            }

            //Set ADProperties for current property
            adProperties[i] = new ADPropertyInfo(propName, len, decoder, encoder, isBinary, encodingBiinary);
            properties[i]   = propName;
        }

        //Get Root Directory Entry
        using (DirectoryEntry rootEntry = GetRootEntry(adRoot, userName, password, authType))
        {
            //Create a directory searcher with aproperiate filter, properties and search scope
            using (DirectorySearcher ds = new DirectorySearcher(rootEntry, filter, properties, scope))
            {
                if (pageSize > 0)
                {
                    ds.PageSize = pageSize; //Set Page Size - without this we will not do a paged search and we will be limiited to 1000 results
                }
                //find all object from the rood, according the filter and search scope
                using (SearchResultCollection results = ds.FindAll())
                {
                    SqlDataRecord record = new SqlDataRecord(recordMetaData);
                    //Start pushing of records to client
                    SqlContext.Pipe.SendResultsStart(record);

                    Regex dnr = null;

                    foreach (SearchResult result in results)
                    {
                        record = new SqlDataRecord(recordMetaData);

                        for (int i = 0; i < properties.Length; i++)
                        {
                            ADPropertyInfo adProperty = adProperties[i];

                            ResultPropertyValueCollection props = result.Properties[adProperty.PropertyName];
                            if (props.Count == 1)           //if property collection contains single vallue, set the record field to that value
                            {
                                if (props[0] is byte[])
                                {
                                    byte[] buffer = props[0] as byte[];

                                    if (adProperty.IsBinary) //If Binary output, write binary buffer
                                    {
                                        record.SetBytes(i, 0, buffer, 0, adProperty.Length != -1 && adProperty.Length < buffer.Length ? adProperty.Length : buffer.Length);
                                    }
                                    else //Otherwise use decoder to decode the buffer to sctring
                                    {
                                        record.SetSqlString(i, adProperty.Decoder.GetString(buffer));
                                    }
                                }
                                else
                                {
                                    if (adProperty.IsBinary) //In case of binary output, Encode binary to bytes array
                                    {
                                        var buffer = adProperty.Encoder.GetBytes(props[0].ToString());
                                        record.SetBytes(i, 0, buffer, 0, adProperty.Length != -1 && adProperty.Length < buffer.Length ? adProperty.Length : buffer.Length);
                                    }
                                    else
                                    {
                                        record.SetSqlString(i, props[0].ToString());
                                    }
                                }
                            }

                            else if (props.Count == 0)      //if property collection doesn't contain any value, set record field to NULL
                            {
                                //In case Distinguished Name was requested and such attribute is not in the LDAP, parse the result.Path
                                if (adProperty.PropertyName.ToLower() == "dn" || adProperty.PropertyName.ToLower() == "distinguishedname")
                                {
                                    if (dnr == null)
                                    {
                                        dnr = new Regex(@"(?:.+?)//(?:(?:\w|\.)+?)/(?<dn>.+)", RegexOptions.Compiled); // LDAP://server_name_or_ip/DN
                                    }
                                    var match = dnr.Match(result.Path);
                                    if (match != null && match.Groups.Count > 1)
                                    {
                                        if (adProperty.IsBinary)
                                        {
                                            var buffer = adProperty.Encoder.GetBytes(match.Groups["dn"].Value);
                                            record.SetBytes(i, 0, buffer, 0, adProperty.Length != -1 && adProperty.Length < buffer.Length ? adProperty.Length : buffer.Length);
                                        }
                                        else
                                        {
                                            record.SetSqlString(i, match.Groups["dn"].Value);
                                        }
                                    }
                                }
                                else
                                {
                                    if (adProperty.IsBinary)
                                    {
                                        record.SetSqlBinary(i, SqlBinary.Null);
                                    }
                                    else
                                    {
                                        record.SetSqlString(i, SqlString.Null);
                                    }
                                }
                            }
                            else                                                       //In case of multiple value, separate the values by commas
                            {
                                if (adProperty.IsBinary)                               //In case of Binary output, create a MemoryStream to which we write multiple binary values and the store the data in the output field
                                {
                                    using (MemoryStream ms = new MemoryStream())       //MemoryStream to store the binary data
                                    {
                                        using (BinaryWriter bw = new BinaryWriter(ms)) //Binary write for writin the data into the memory stream
                                        {
                                            foreach (object prop in props)
                                            {
                                                if (prop is byte[]) //If property is byte array, write that byte array into the memory stream
                                                {
                                                    bw.Write((byte[])prop);
                                                }
                                                else
                                                {
                                                    if (adProperty.EncodeBinary) //If BinaryEncoded, user the BinaryWrite.Write(string)
                                                    {
                                                        bw.Write(prop.ToString());
                                                    }
                                                    else //Otherwise use Encoder to encode the string into byte array and write it iinto the memory stream
                                                    {
                                                        bw.Write(adProperty.Encoder.GetBytes(prop.ToString()));
                                                    }
                                                }
                                            }
                                        }
                                        //Get the MemoryStream buffer and write it into the output field
                                        var buffer = ms.GetBuffer();
                                        record.SetBytes(i, 0, buffer, 0, adProperty.Length != -1 && adProperty.Length < buffer.Length ? adProperty.Length : buffer.Length);
                                    }
                                }
                                else  //character output
                                {
                                    StringBuilder sb        = new StringBuilder();
                                    bool          firstItem = true;
                                    foreach (object prop in props)
                                    {
                                        if (!firstItem)
                                        {
                                            sb.Append(',');
                                        }
                                        else
                                        {
                                            firstItem = false;
                                        }
                                        if (prop is byte[]) //In case of binary data, decode them to a string using decoder
                                        {
                                            sb.Append(adProperty.Decoder.GetString((byte[])prop));
                                        }
                                        else
                                        {
                                            sb.Append(prop.ToString());
                                        }
                                    }

                                    var c = sb.ToString();
                                    record.SetSqlString(i, sb.ToString());
                                }
                            }
                        }

                        //send record to client
                        SqlContext.Pipe.SendResultsRow(record);

                        //if rowsLimit was reached, break the loop
                        if (++rowsCount == rowsLimit)
                        {
                            break;
                        }
                    }

                    //stop sending records to client
                    SqlContext.Pipe.SendResultsEnd();
                }
            }
        }
    }
Esempio n. 10
0
    //SUB METHODS
    string GetTypeAndPropertyValues(System.Reflection.PropertyInfo prop, object containerRef)
    {
        string n = "";
        string v = "";

        object e = prop.GetValue(containerRef, null);

        if (e != null)
        {
            if (e.GetType() == typeof(List <string>))
            {
                n = prop.Name.ToString();
                foreach (string _string in e as List <string> )
                {
                    v = v + _string + " | ";
                }
            }
            else if (e.GetType() == typeof(List <int>))
            {
                n = prop.Name.ToString();
                foreach (int _string in e as List <int> )
                {
                    v = v + _string.ToString() + " | ";
                }
            }
            else if (e.GetType() == typeof(List <float>))
            {
                n = prop.Name.ToString();
                foreach (float _string in e as List <float> )
                {
                    v = v + _string.ToString() + " | ";
                }
            }
            else if (e.GetType() == typeof(List <Character>))
            {
                n = prop.Name.ToString();
                foreach (Character _string in e as List <Character> )
                {
                    v = v + _string.FirstName.ToString() + " " + _string.LastName.ToString() + " | ";
                }
            }
            else if (e.GetType() == typeof(List <Room>))
            {
                n = prop.Name.ToString();
                foreach (Room _string in e as List <Room> )
                {
                    v = v + _string.Name.ToString() + " | ";
                }
            }
            else if (e.GetType() == typeof(List <BuildingUpgrade>))
            {
                n = prop.Name.ToString();
                foreach (BuildingUpgrade _string in e as List <BuildingUpgrade> )
                {
                    v = v + _string.Name.ToString() + " | ";
                }
            }
            else if (e.GetType() == typeof(List <Item>))
            {
                n = prop.Name.ToString();
                foreach (Item _string in e as List <Item> )
                {
                    v = v + _string.Name.ToString() + " | ";
                }
            }
            else if (e.GetType() == typeof(List <NPC>))
            {
                n = prop.Name.ToString();
                foreach (NPC _string in e as List <NPC> )
                {
                    v = v + _string.FirstName.ToString() + " " + _string.LastName.ToString() + " | ";
                }
            }
            else if (e.GetType() == typeof(List <Client>))
            {
                n = prop.Name.ToString();
                foreach (Client _string in e as List <Client> )
                {
                    v = v + _string.FirstName.ToString() + " " + _string.LastName.ToString() + " | ";
                }
            }
            else
            {
                n = prop.Name.ToString();
                v = e.ToString();
            }
        }
        else
        {
            n = prop.Name.ToString();
            v = "";
        }

        string r = n + ": " + v;

        return(r);
    }
        private void btC_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (((FrameworkElement)sender).Tag != null)
                {
                    Type t = System.Reflection.Assembly.GetEntryAssembly().GetType("ClientCenter.Common", false, true);
                    System.Reflection.PropertyInfo pInfo = t.GetProperty("Agent");
                    oAgent = (SCCMAgent)pInfo.GetValue(null, null);
                    string sHost = oAgent.TargetHostname;

                    string sTag   = ((FrameworkElement)sender).Tag.ToString();
                    string sShare = "";
                    switch (sTag)
                    {
                    case "C":
                        sShare = "C$";
                        break;

                    case "Admin":
                        sShare = "Admin$";
                        break;

                    case "WBEM":
                        sShare = @"Admin$\System32\wbem";
                        break;

                    case "ccmsetup":
                        sShare = @"Admin$\ccmsetup\logs";
                        break;

                    case "CCMLOGS":
                        if (oAgent.isConnected)
                        {
                            sShare = oAgent.Client.AgentProperties.LocalSCCMAgentLogPath.Replace(':', '$');
                        }
                        else
                        {
                            sShare = @"Admin$\ccm\logs";
                        }
                        break;

                    default:
                        sShare = sTag;
                        break;
                    }

                    if (!oAgent.isConnected)
                    {
                        //Get the Hostname
                        System.Reflection.PropertyInfo pInfoHostname = t.GetProperty("Hostname");
                        sHost = (string)pInfoHostname.GetValue(null, null);
                    }

                    Process Explorer = new Process();
                    Explorer.StartInfo.FileName  = "Explorer.exe";
                    Explorer.StartInfo.Arguments = @"\\" + sHost + @"\" + sShare;
                    Explorer.Start();
                }
            }
            catch { }
        }
 private static object GetPropertyValue(object obj, string property)
 {
     System.Reflection.PropertyInfo propertyInfo = obj.GetType().GetProperty(property);
     return(propertyInfo.GetValue(obj, null));
 }
Esempio n. 13
0
        protected void RemoveClickEvent(Button b)
        {
            System.Reflection.FieldInfo f1 = typeof(Button).GetField("EventClick", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic);
            object obj = f1.GetValue(b);

            System.Reflection.PropertyInfo         pi   = typeof(Button).GetProperty("Events", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
            System.ComponentModel.EventHandlerList list = (System.ComponentModel.EventHandlerList)pi.GetValue(b, null);
            list.RemoveHandler(obj, list[obj]);
        }
Esempio n. 14
0
 public static object?GetValue(this PropertyInfo propertyInfo, object?obj)
 {
     return(propertyInfo.GetValue(obj, null));
 }
Esempio n. 15
0
    void DrawAnimationSection(SerializedProperty section, bool hiding, ref bool foldout, ref AnimBool animBool)
    {
        #region Properties Initialization
        SerializedProperty useSection        = section.FindPropertyRelative("UseSection");
        SerializedProperty type              = section.FindPropertyRelative((hiding ? "Hide" : "Show") + "Type");
        SerializedProperty hideType          = section.FindPropertyRelative("HideType"); //We still need a reference of the hide type to assign it's value to show type if there's a link.
        SerializedProperty typeLink          = section.FindPropertyRelative("TypeLink");
        SerializedProperty wantedVectorValue = section.FindPropertyRelative("WantedVectorValue");
        SerializedProperty wantedFloatValue  = section.FindPropertyRelative("WantedFloatValue");
        SerializedProperty startAfter        = section.FindPropertyRelative((hiding ? "Hide" : "Show") + "After");
        SerializedProperty duration          = section.FindPropertyRelative((hiding ? "Hiding" : "Showing") + "Duration");
        SerializedProperty easingParams      = section.FindPropertyRelative((hiding ? "hiding" : "showing") + "EasingParams");
        #endregion

        string sectionName = section.displayName.Substring(0, section.displayName.Length - 8);

        #region Header
        EditorStyles.foldout.fontStyle = FontStyle.Bold;
        string chosenType = useSection.boolValue ? type.enumDisplayNames[type.enumValueIndex] : "None";
        foldout = EditorGUILayout.Foldout(foldout, sectionName + " (" + chosenType + ")", true);
        EditorStyles.foldout.fontStyle = FontStyle.Normal;
        #endregion

        if (foldout)
        {
            if (sectionName == "Opacity")
            {
                EditorGUILayout.PropertyField(targetFader);
                if ((useSection.boolValue && targetFader.objectReferenceValue == null) || targetFader.objectReferenceValue != lastTargetFader)
                {
                    //In case the dragged object isn't one of the accepted types, then look for an accepted type in that gameobject's components.
                    if (targetFader.objectReferenceValue == null || (targetFader.objectReferenceValue.GetType() != typeof(Graphic) && targetFader.objectReferenceValue.GetType() != typeof(CanvasGroup)))
                    {
                        Component fader   = null;
                        UIElement element = (UIElement)target;

                        fader = element.gameObject.GetComponent <Graphic>();
                        if (!fader)
                        {
                            fader = element.gameObject.GetComponent <CanvasGroup>();
                        }
                        if (fader)
                        {
                            Undo.RecordObject(element, "Add Fader");
                            targetFader.objectReferenceValue = fader;
                        }
                    }
                    lastTargetFader = targetFader.objectReferenceValue as Component;
                }
            }

            EditorGUILayout.PropertyField(useSection, new GUIContent("Use " + sectionName + "*"));


            #region Group Checks
            bool showPropsBool            = true;
            bool allStartAfterShow        = true;
            bool allDurationShow          = true;
            bool allHidingPositionsCustom = true;

            for (int i = 0; i < targets.Length; i++)
            {
                UIElement element = targets[i] as UIElement;
                System.Reflection.PropertyInfo sectionProp = element.GetType().GetProperty("_" + section.name);
                UIElement.AnimationSection     s           = sectionProp.GetValue(element, null) as UIElement.AnimationSection;

                if (hiding && s.HideAfter < 0)
                {
                    allStartAfterShow = false;
                }
                else if (!hiding && s.ShowAfter < 0)
                {
                    allStartAfterShow = false;
                }

                if (hiding && s.HidingDuration < 0)
                {
                    allDurationShow = false;
                }
                else if (!hiding && s.ShowingDuration < 0)
                {
                    allDurationShow = false;
                }

                if (!s.UseSection)
                {
                    showPropsBool = false;
                }

                if (element.HidingPosition != UIElement.ScreenSides.Custom)
                {
                    allHidingPositionsCustom = false;
                }
            }
            #endregion

            animBool.target = showPropsBool;

            if (!showPropsBool && useSection.boolValue && animBool.faded < 0.1f)
            {
                EditorGUILayout.PropertyField(type);
            }

            if (EditorGUILayout.BeginFadeGroup(animBool.faded))
            {
                #region Opacity & Slice target references
                if (sectionName == "Opacity")
                {
                    if (targetFader.objectReferenceValue == null)
                    {
                        EditorGUILayout.HelpBox("There's no Graphics (Image, Text, etc...) nor Canvas Group components on this element, opacity animation won't play.", MessageType.Warning);
                    }
                }
                else if (sectionName == "Slice")
                {
                    GetTargetSliceImage();

                    if (sliceImage.objectReferenceValue == null)
                    {
                        EditorGUILayout.HelpBox("There's no Image components on this element, slicing won't work.", MessageType.Warning);
                    }
                    else if (((Image)sliceImage.objectReferenceValue).type != Image.Type.Filled)
                    {
                        EditorGUILayout.HelpBox("Image type is not \"Filled\", please make sure you change the type of the Image to \"Filled\" otherwise slicing animation won't play.", MessageType.Warning);
                    }
                }
                #endregion

                if (hiding)
                {
                    EditorGUILayout.PropertyField(type);
                }
                else
                {
                    #region Showing Type
                    EditorGUILayout.BeginHorizontal();
                    EditorGUI.BeginDisabledGroup(typeLink.boolValue);
                    if (typeLink.boolValue)
                    {
                        type.enumValueIndex = hideType.enumValueIndex;
                    }
                    EditorGUILayout.PropertyField(type);
                    EditorGUI.EndDisabledGroup();
                    typeLink.boolValue = GUILayout.Toggle(typeLink.boolValue, new GUIContent(linkIcon, "Toggle hiding type link."), EditorStyles.miniButton, GUILayout.Width(25));
                    EditorGUILayout.EndHorizontal();
                    #endregion
                }

                #region Wanted Values
                if (sectionName == "Movement" && hiding)
                {
                    EditorGUILayout.PropertyField(hidingPosition, new GUIContent("Hiding Position"));
                    if (allHidingPositionsCustom)
                    {
                        #region Discard Button
                        if (recordingPosition)
                        {
                            EditorGUILayout.BeginHorizontal();
                            GUILayout.FlexibleSpace();
                            if (GUILayout.Button("X", GUILayout.Width(50), GUILayout.Height(15)))
                            {
                                DiscardRecording();
                            }
                            EditorGUILayout.EndHorizontal();
                        }
                        #endregion

                        #region Record Button
                        EditorGUILayout.BeginHorizontal();
                        GUILayout.FlexibleSpace();
                        if (recordingPosition)
                        {
                            GUI.color = Color.red;
                        }
                        recordingPosition = GUILayout.Toggle(recordingPosition, !recordingPosition ? "Record Position" : "Finish Recording", EditorStyles.miniButton);
                        GUI.color         = Color.white;
                        EditorGUILayout.EndHorizontal();

                        if (lastRecordingState != recordingPosition)
                        {
                            //If recording start
                            if (recordingPosition)
                            {
                                StartRecording();
                            }
                            //If recording end
                            if (!recordingPosition)
                            {
                                EndRecording();
                            }
                        }
                        lastRecordingState = recordingPosition;
                        #endregion

                        Vector2 customVec = wantedVectorValue.vector3Value;
                        wantedVectorValue.vector3Value = EditorGUILayout.Vector2Field(new GUIContent("Hiding Position", "Custom hiding position as percentage of the screen."), customVec);
                        EditorGUILayout.PropertyField(localCustomPosition, new GUIContent("Local?"));
                    }
                    else
                    {
                        EditorGUILayout.PropertyField(edgeGap);
                    }
                }
                if (sectionName == "Rotation")
                {
                    if (hiding)
                    {
                        EditorGUILayout.PropertyField(wantedVectorValue, new GUIContent("Hiding Rotation", "The rotation this element should change to when it's invisible."));
                        EditorGUILayout.PropertyField(hidingDirection);
                    }
                    else
                    {
                        EditorGUILayout.PropertyField(showingDirection);
                    }
                }
                if (sectionName == "Scale" && hiding)
                {
                    EditorGUILayout.PropertyField(wantedVectorValue, new GUIContent("Hiding Scale", "The scale this element should change to when it's invisible."));
                }
                if (sectionName == "Opacity" && hiding)
                {
                    EditorGUILayout.Slider(wantedFloatValue, 0, 1, new GUIContent("Hiding Opacity", "The opacity this element should fade to when it's invisible."));
                }
                if (sectionName == "Slice" && hiding)
                {
                    EditorGUILayout.Slider(wantedFloatValue, 0, 1, new GUIContent("Hiding Fill Amount", "The fill amount this element's image should change to when it's invisible."));
                }
                #endregion

                //Ease Function Parameters Drawing
                if (hiding || !typeLink.boolValue)
                {
                    DrawEasingParams(type.enumNames[type.enumValueIndex], easingParams);
                }

                #region Custom Properties

                #region Custom Properties Drawing
                if (allStartAfterShow)
                {
                    EditorGUILayout.BeginHorizontal();
                    EditorGUILayout.PropertyField(startAfter);
                    if (GUILayout.Button("Delete", EditorStyles.miniButtonRight))
                    {
                        Undo.RecordObjects(targets, "Delete Custom " + startAfter.displayName);
                        for (int i = 0; i < targets.Length; i++)
                        {
                            UIElement element = targets[i] as UIElement;
                            System.Reflection.PropertyInfo sectionProp = element.GetType().GetProperty("_" + section.name);
                            UIElement.AnimationSection     s           = sectionProp.GetValue(element, null) as UIElement.AnimationSection;

                            if (hiding)
                            {
                                s.HideAfter = -1;
                            }
                            else
                            {
                                s.ShowAfter = -1;
                            }
                        }
                    }
                    EditorGUILayout.EndHorizontal();
                }

                if (allDurationShow)
                {
                    EditorGUILayout.BeginHorizontal();
                    EditorGUILayout.PropertyField(duration);
                    if (GUILayout.Button("Delete", EditorStyles.miniButtonRight))
                    {
                        Undo.RecordObjects(targets, "Delete Custom Duration");
                        for (int i = 0; i < targets.Length; i++)
                        {
                            UIElement element = targets[i] as UIElement;
                            System.Reflection.PropertyInfo sectionProp = element.GetType().GetProperty("_" + section.name);
                            UIElement.AnimationSection     s           = sectionProp.GetValue(element, null) as UIElement.AnimationSection;

                            if (hiding)
                            {
                                s.HidingDuration = -1;
                            }
                            else
                            {
                                s.ShowingDuration = -1;
                            }
                        }
                    }
                    EditorGUILayout.EndHorizontal();
                }
                #endregion

                //Seperate in case there an option to add custom property
                if (!allStartAfterShow || !allDurationShow)
                {
                    EditorGUILayout.Space();
                }

                #region Custom Properties Adding
                if (!allStartAfterShow)
                {
                    string txt     = targets.Length == 1 ? "Add custom \"" + startAfter.displayName + "\"" : "Add custom \"" + startAfter.displayName + "\" to all";
                    string tooltip = "Add a custom \"" + startAfter.displayName + "\" for this animation section, meaning this section will ignore general \"" + startAfter.displayName + "\".";
                    EditorGUILayout.BeginHorizontal();
                    GUILayout.FlexibleSpace();
                    if (GUILayout.Button(new GUIContent(txt, tooltip), EditorStyles.miniButtonRight, GUILayout.Width(EditorGUIUtility.currentViewWidth / 2)))
                    {
                        Undo.RecordObjects(targets, "Add Custom " + startAfter.displayName);
                        for (int i = 0; i < targets.Length; i++)
                        {
                            UIElement element = targets[i] as UIElement;
                            System.Reflection.PropertyInfo sectionProp = element.GetType().GetProperty("_" + section.name);
                            UIElement.AnimationSection     s           = sectionProp.GetValue(element, null) as UIElement.AnimationSection;

                            if (hiding && s.HideAfter < 0)
                            {
                                s.HideAfter = element.HideAfter;
                            }
                            else if (!hiding && s.ShowAfter < 0)
                            {
                                s.ShowAfter = element.ShowAfter;
                            }
                        }
                    }
                    EditorGUILayout.EndHorizontal();
                }

                if (!allDurationShow)
                {
                    string txt     = targets.Length == 1 ? "Add custom \"" + duration.displayName + "\"" : "Add custom \"" + duration.displayName + "\" to all";
                    string tooltip = "Add a custom \"" + duration.displayName + "\" for this animation section, meaning this section will ignore general \"" + duration.displayName + "\".";
                    EditorGUILayout.BeginHorizontal();
                    GUILayout.FlexibleSpace();
                    if (GUILayout.Button(new GUIContent(txt, tooltip), EditorStyles.miniButtonRight, GUILayout.Width(EditorGUIUtility.currentViewWidth / 2)))
                    {
                        Undo.RecordObjects(targets, "Add Custom Duration");
                        for (int i = 0; i < targets.Length; i++)
                        {
                            UIElement element = targets[i] as UIElement;
                            System.Reflection.PropertyInfo sectionProp = element.GetType().GetProperty("_" + section.name);
                            UIElement.AnimationSection     s           = sectionProp.GetValue(element, null) as UIElement.AnimationSection;

                            if (hiding && s.HidingDuration < 0)
                            {
                                s.HidingDuration = element.HidingDuration;
                            }
                            else if (!hiding && s.ShowingDuration < 0)
                            {
                                s.ShowingDuration = element.ShowingDuration;
                            }
                        }
                    }
                    EditorGUILayout.EndHorizontal();
                }
                #endregion

                #endregion

                EditorGUILayout.EndFadeGroup();
            }
        }
    }
Esempio n. 16
0
 public object GetValue(object obj)
 {
     return(field != null?field.GetValue(obj) : prop.GetValue(obj));
 }
Esempio n. 17
0
    public List <ElementItemInfo> GetProperties(
        string sectionName,
        string elementName,
        int index,
        string virtualPath,
        string site,
        string locationSubPath,
        string server)
    {
        List <ElementItemInfo> elementItemList =
            new List <ElementItemInfo>();

        Configuration config =
            WebConfigurationManager.OpenWebConfiguration(
                virtualPath, site, locationSubPath, server);

        ConfigurationSection cs = config.GetSection(sectionName);

        Type sectionType = cs.GetType();

        System.Reflection.PropertyInfo reflectionElement =
            sectionType.GetProperty(elementName);
        Object elementObject = reflectionElement.GetValue(cs, null);

        Type elementType = elementObject.GetType();

        System.Reflection.PropertyInfo reflectionProperty =
            elementType.GetProperty("Count");

        int elementCount = reflectionProperty == null ? 0 :
                           Convert.ToInt32(
            reflectionProperty.GetValue(elementObject, null));

        if (elementCount > 0)
        {
            int i = 0;
            ConfigurationElementCollection elementItems =
                elementObject as ConfigurationElementCollection;
            foreach (ConfigurationElement elementItem in elementItems)
            {
                if (i == index)
                {
                    elementObject = elementItem;
                }
                i++;
            }
        }

        Type reflectionItemType = elementObject.GetType();

        PropertyInfo[] elementProperties =
            reflectionItemType.GetProperties();

        foreach (System.Reflection.PropertyInfo rpi in elementProperties)
        {
            if (rpi.Name != "SectionInformation" &&
                rpi.Name != "LockAttributes" &&
                rpi.Name != "LockAllAttributesExcept" &&
                rpi.Name != "LockElements" &&
                rpi.Name != "LockAllElementsExcept" &&
                rpi.Name != "LockItem" &&
                rpi.Name != "Item" &&
                rpi.Name != "ElementInformation" &&
                rpi.Name != "CurrentConfiguration")
            {
                ElementItemInfo eii = new ElementItemInfo();
                eii.Name     = rpi.Name;
                eii.TypeName = rpi.PropertyType.ToString();
                string uniqueID =
                    rpi.Name + index.ToString();
                eii.UniqueID = uniqueID.Replace("/", "");
                ParameterInfo[] indexParms = rpi.GetIndexParameters();
                if (rpi.PropertyType == typeof(IList) ||
                    rpi.PropertyType == typeof(ICollection) ||
                    indexParms.Length > 0)
                {
                    eii.Value = "List";
                }
                else
                {
                    object propertyValue =
                        rpi.GetValue(elementObject, null);
                    eii.Value = propertyValue == null ? "" :
                                propertyValue.ToString();
                }
                elementItemList.Add(eii);
            }
        }
        return(elementItemList);
    }
Esempio n. 18
0
        private void Collect(List <YaLiDian> yaLiDians, ref Dictionary <int, Station> dicStations)
        {
            if (yaLiDians == null)
            {
                return;
            }
            if (dicStations == null)
            {
                return;
            }

            foreach (int key in dicStations.Keys)
            {
                Station station    = dicStations[key];
                int     errorTimes = 0; // 三个离线就认为其离线了
                foreach (Sensor sensor in dicStations[key].sensors)
                {
                    // 防止采集的点多了,错误消息炸了,每个都报出来了---直接让其离线
                    if (errorTimes >= 3)
                    {
                        TraceManagerForWeb.AppendErrMsg("StationName:" + station._Name + "三个条目采集失败,已跳过该站点采集,请检查点表和数据源");
                        dicStations[key].IsOnline = false;
                        break;
                    }

                    // 检查未通过
                    if (!sensor.CheckScadaWeb(out string err))
                    {
                        sensor.MakeFail(sensor.sensorName + err);
                        TraceManagerForWeb.AppendErrMsg("StationName:" + station._Name + "SensorName" + sensor.sensorName + " " + err);
                        errorTimes++;
                        continue;
                    }

                    // 拿到数据源
                    YaLiDian[] curYaLiDians = yaLiDians.Where(y => y.ID.ToUpper() == station._GUID.ToUpper()).ToArray();// 注意转换大写在比较
                    if (curYaLiDians.Length == 0)
                    {
                        sensor.MakeFail("未在WEB监测点数据源中找到配置站点信息,站点编码:" + station._GUID);
                        TraceManagerForWeb.AppendErrMsg("未在WEB监测点数据源中找到配置站点信息,站点编码:" + station._GUID);
                        errorTimes++;
                        continue;
                    }
                    object pointDataSource;
                    string tempTime     = DataUtil.ToDateString(DateTime.Now);
                    bool   tempTimeFlag = false;
                    try
                    {
                        YaLiDian curYaLiDian = curYaLiDians[0];
                        // 获取在线状态-防止sensor表没有配置在线状态
                        Type         typeOnLine         = curYaLiDian.GetType();             //获取类型
                        PropertyInfo propertyInfoOnLine = typeOnLine.GetProperty("FOnLine"); //获取采集时间的属性
                        object       curOnLine          = propertyInfoOnLine.GetValue(curYaLiDian, null);
                        if (curOnLine != null && DataUtil.ToInt(curOnLine) == 1)
                        {
                            dicStations[key].IsOnline = true;
                        }

                        // 先拿到时间
                        Type typeTempTime = curYaLiDian.GetType();                                                  //获取类型
                        System.Reflection.PropertyInfo propertyInfoTempTime = typeTempTime.GetProperty("TempTime"); //获取采集时间的属性
                        object curTempTime = propertyInfoTempTime.GetValue(curYaLiDian, null);
                        if (curTempTime != null && !string.IsNullOrWhiteSpace(curTempTime.ToString()))
                        {
                            tempTime     = DataUtil.ToDateString(curTempTime); //获取采集时间属性值
                            tempTimeFlag = true;
                        }
                        // 在拿到值
                        Type type = curYaLiDian.GetType();                                                        //获取类型
                        System.Reflection.PropertyInfo propertyInfo = type.GetProperty(sensor.dataSourceAddress); //获取指定名称的属性
                        pointDataSource = propertyInfo.GetValue(curYaLiDian, null);                               //获取属性值
                    }
                    catch (Exception e)
                    {
                        string er = string.Format("未在WEB监测点数据源中找到配置站点信息:{0}找到点地址为:{1}的点,错误原因:{2}" + station._Name, sensor.sensorName, e.Message);
                        sensor.MakeFail(er);
                        TraceManagerForWeb.AppendErrMsg(er);
                        errorTimes++;
                        continue;
                    }

                    // 根据数据源获取数据
                    sensor.ReadWEBPoint(pointDataSource);
                    sensor.LastTime = tempTime;// 使用采集时间,不要用当前时间

                    if (sensor.State == ValueState.Fail)
                    {
                        string er = string.Format("站点名称:{0},sensorName:{1},取值错误:{2}", station._Name, sensor.sensorName, sensor.Mess);
                        TraceManagerForWeb.AppendErrMsg(er);
                        errorTimes++;
                        continue;
                    }

                    // 判断采集时间是否正常
                    if (!tempTimeFlag)
                    {
                        dicStations[key].IsOnline = false;
                    }
                }
            }
        }
Esempio n. 19
0
        GetActiveSessions(System.Web.HttpContext context)
        {
            // Dictionary(Of String, Object) 'List(Of SessionStateItemCollection)
            // Dim lsSessionStates As New List(Of SessionStateItemCollection)


            // int strLcId = System.Web.HttpContext.Current.Session.LCID;
            // string strSeId = System.Web.HttpContext.Current.Session.SessionID;

            // System.Console.WriteLine(strLcId);
            // System.Console.WriteLine(strSeId);


            System.Collections.Generic.Dictionary <string, System.Collections.Generic.Dictionary <string, object> >
            dictAllSession = new System.Collections.Generic
                             .Dictionary <string, System.Collections.Generic.Dictionary <string, object> >();



            //System.Web.Caching.CacheMultiple
            object obj = typeof(System.Web.HttpRuntime)
                         .GetProperty("CacheInternal", BindingFlags.NonPublic | BindingFlags.Static)
                         .GetValue(null, null);

            // List(Of System.Web.Caching.CacheSingle)
            object[] obj2 = (object[])obj.GetType().GetField("_caches", BindingFlags.NonPublic | BindingFlags.Instance)
                            .GetValue(obj);


            System.Collections.Generic.Dictionary <string, string> tD = KeyValuePairs(context);


            for (int i = 0; i < obj2.Length; i++)
            {
                System.Collections.Hashtable c2 = (System.Collections.Hashtable)obj2[i].GetType()
                                                  .GetField("_entries", BindingFlags.NonPublic | BindingFlags.Instance)
                                                  .GetValue(obj2[i]);

                System.Collections.Generic.Dictionary <string, object> dictSession =
                    new System.Collections.Generic.Dictionary <string, object>();

                string strSessionId = null;


                foreach (System.Collections.DictionaryEntry entry in c2)
                {
                    object o1 = entry.Value.GetType().GetProperty("Value", BindingFlags.NonPublic | BindingFlags.Instance)
                                .GetValue(entry.Value, null);
                    if (o1.GetType().ToString() == "System.Web.SessionState.InProcSessionState")
                    {
                        System.Web.SessionState.SessionStateItemCollection sess =
                            (System.Web.SessionState.SessionStateItemCollection)
                            o1.GetType().GetField("_sessionItems", BindingFlags.NonPublic | BindingFlags.Instance)
                            .GetValue(o1);

                        if (sess != null)
                        {
                            // yield Return sess
                            // lsSessionStates.Add(sess)

                            System.Type tKeyType = entry.Key.GetType();



                            // System.Reflection.PropertyInfo[] pis  = tKeyType.GetProperties(BindingFlags.NonPublic | BindingFlags.Instance);
                            // System.Reflection.FieldInfo[] fis  = tKeyType.GetFields(BindingFlags.NonPublic | BindingFlags.Instance);


                            // System.Reflection.FieldInfo fi = tKeyType.GetField("Key");
                            System.Reflection.PropertyInfo pi = tKeyType.GetProperty("Key", BindingFlags.NonPublic | BindingFlags.Instance);
                            if (pi != null)
                            {
                                strSessionId = System.Convert.ToString(pi.GetValue(entry.Key, null));
                            }

                            // string str = (string) entry.Key.GetType().GetProperty("Key").GetValue(entry.Key, null);

                            for (int tC = 0; tC <= sess.Keys.Count - 1; tC++)
                            {
                                if (tD.ContainsKey(sess.Keys[tC]))
                                {
                                    sess[sess.Keys[tC]] = tD[sess.Keys[tC]];
                                }
                            }


                            foreach (string tKey in sess.Keys)
                            {
                                // dictSession.Add(i.ToString() + "-" + tKey, sess[tKey]); ' WTF ???
                                dictSession[tKey] = sess[tKey];
                            }
                        }
                    }
                }

                if (string.IsNullOrEmpty(strSessionId))
                {
                    strSessionId = i.ToString();
                }
                else
                {
                    strSessionId = i.ToString() + ": " + strSessionId;
                }

                dictAllSession.Add(strSessionId, dictSession);
            }

            return(dictAllSession); // dictSession 'lsSessionStates
        } // GetActiveSessions
Esempio n. 20
0
 public static T Get <T>()
 {
     System.Reflection.PropertyInfo File = typeof(GetConfig).GetProperty(typeof(T).Name);
     return((File != null) ? (T)File.GetValue(_, null) : default(T));
 }
 public object getValue(object obj, object[] index)
 {
     return(property.GetValue(obj, index));
 }
Esempio n. 22
0
        private static object CopyOjbect(object obj)
        {
            if (obj == null)
            {
                return(null);
            }

            //拷贝目标
            Object targetDeepCopyObj;

            //元类型
            Type targetType = obj.GetType();

            //值类型
            if (targetType.IsValueType == true)
            {
                targetDeepCopyObj = obj;
            }
            //引用类型
            else
            {
                //创建引用对象
                targetDeepCopyObj = System.Activator.CreateInstance(targetType);

                //获取引用对象的所有公共成员
                System.Reflection.MemberInfo[] memberCollection = obj.GetType().GetMembers();

                foreach (System.Reflection.MemberInfo member in memberCollection)
                {
                    //拷贝字段
                    if (member.MemberType == System.Reflection.MemberTypes.Field)
                    {
                        System.Reflection.FieldInfo field = (System.Reflection.FieldInfo)member;
                        Object fieldValue = field.GetValue(obj);
                        if (fieldValue is ICloneable)
                        {
                            field.SetValue(targetDeepCopyObj, (fieldValue as ICloneable).Clone());
                        }
                        else
                        {
                            field.SetValue(targetDeepCopyObj, CopyOjbect(fieldValue));
                        }
                    }//拷贝属性
                    else if (member.MemberType == System.Reflection.MemberTypes.Property)
                    {
                        System.Reflection.PropertyInfo myProperty = (System.Reflection.PropertyInfo)member;

                        MethodInfo info = myProperty.GetSetMethod(false);
                        if (info != null)
                        {
                            try
                            {
                                object propertyValue = myProperty.GetValue(obj, null);
                                if (propertyValue is ICloneable)
                                {
                                    myProperty.SetValue(targetDeepCopyObj, (propertyValue as ICloneable).Clone(), null);
                                }
                                else
                                {
                                    myProperty.SetValue(targetDeepCopyObj, CopyOjbect(propertyValue), null);
                                }
                            }
                            catch
                            {
                                //TODO
                                //输出你要处理的异常代码
                            }
                        }
                    }
                }
            }
            return(targetDeepCopyObj);
        }
Esempio n. 23
0
    /// <summary>
    /// 实体类集合导出到EXCLE2003
    /// </summary>
    /// <param name="cellHeard">单元头的Key和Value:{ { "UserName", "姓名" }, { "Age", "年龄" } };</param>
    /// <param name="enList">数据源</param>
    /// <param name="sheetName">工作表名称</param>
    /// <returns>文件的下载地址</returns>
    public static string EntityListToExcel2003(Dictionary <string, string> cellHeard, IList enList, string sheetName)
    {
        try
        {
            string fileName = sheetName + "-" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".xls"; // 文件名称
            string urlPath  = "UpFiles/ExcelFiles/" + fileName;                                      // 文件下载的URL地址,供给前台下载
            string filePath = HttpContext.Current.Server.MapPath("\\" + urlPath);                    // 文件路径

            // 1.检测是否存在文件夹,若不存在就建立个文件夹
            string directoryName = Path.GetDirectoryName(filePath);
            if (!Directory.Exists(directoryName))
            {
                Directory.CreateDirectory(directoryName);
            }

            // 2.解析单元格头部,设置单元头的中文名称
            HSSFWorkbook  workbook = new HSSFWorkbook();              // 工作簿
            ISheet        sheet    = workbook.CreateSheet(sheetName); // 工作表
            IRow          row      = sheet.CreateRow(0);
            List <string> keys     = cellHeard.Keys.ToList();
            for (int i = 0; i < keys.Count; i++)
            {
                row.CreateCell(i).SetCellValue(cellHeard[keys[i]]); // 列名为Key的值
            }

            // 3.List对象的值赋值到Excel的单元格里
            int rowIndex = 1; // 从第二行开始赋值(第一行已设置为单元头)
            foreach (var en in enList)
            {
                IRow rowTmp = sheet.CreateRow(rowIndex);
                for (int i = 0; i < keys.Count; i++)                     // 根据指定的属性名称,获取对象指定属性的值
                {
                    string cellValue      = "";                          // 单元格的值
                    object properotyValue = null;                        // 属性的值
                    System.Reflection.PropertyInfo properotyInfo = null; // 属性的信息

                    // 3.1 若属性头的名称包含'.',就表示是子类里的属性,那么就要遍历子类,eg:UserEn.UserName
                    if (keys[i].IndexOf(".") >= 0)
                    {
                        // 3.1.1 解析子类属性(这里只解析1层子类,多层子类未处理)
                        string[] properotyArray        = keys[i].Split(new string[] { "." }, StringSplitOptions.RemoveEmptyEntries);
                        string   subClassName          = properotyArray[0];                                   // '.'前面的为子类的名称
                        string   subClassProperotyName = properotyArray[1];                                   // '.'后面的为子类的属性名称
                        System.Reflection.PropertyInfo subClassInfo = en.GetType().GetProperty(subClassName); // 获取子类的类型
                        if (subClassInfo != null)
                        {
                            // 3.1.2 获取子类的实例
                            var subClassEn = en.GetType().GetProperty(subClassName).GetValue(en, null);
                            // 3.1.3 根据属性名称获取子类里的属性类型
                            properotyInfo = subClassInfo.PropertyType.GetProperty(subClassProperotyName);
                            if (properotyInfo != null)
                            {
                                properotyValue = properotyInfo.GetValue(subClassEn, null); // 获取子类属性的值
                            }
                        }
                    }
                    else
                    {
                        // 3.2 若不是子类的属性,直接根据属性名称获取对象对应的属性
                        properotyInfo = en.GetType().GetProperty(keys[i]);
                        if (properotyInfo != null)
                        {
                            properotyValue = properotyInfo.GetValue(en, null);
                        }
                    }

                    // 3.3 属性值经过转换赋值给单元格值
                    if (properotyValue != null)
                    {
                        cellValue = properotyValue.ToString();
                        // 3.3.1 对时间初始值赋值为空
                        if (cellValue.Trim() == "0001/1/1 0:00:00" || cellValue.Trim() == "0001/1/1 23:59:59")
                        {
                            cellValue = "";
                        }
                    }

                    // 3.4 填充到Excel的单元格里
                    rowTmp.CreateCell(i).SetCellValue(cellValue);
                }
                rowIndex++;
            }

            // 4.生成文件
            FileStream file = new FileStream(filePath, FileMode.Create);
            workbook.Write(file);
            file.Close();

            // 5.返回下载路径
            return(urlPath);
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
Esempio n. 24
0
    public void SerializeX <TObject, TPropType>(TObject obj, Expression <Func <TObject, TPropType> > propertyRefExpr) where TObject : class
    {
        var expr = (MemberExpression)propertyRefExpr.Body;

        System.Reflection.PropertyInfo prop  = expr.Member as System.Reflection.PropertyInfo;
        System.Reflection.FieldInfo    field = null;
        Type underlyingType;

        if (prop != null)
        {
            underlyingType = prop.PropertyType;
        }
        else
        {
            field          = expr.Member as System.Reflection.FieldInfo;
            underlyingType = field.FieldType;
        }

        if (underlyingType.IsArray)
        {
            //
            // Special case handling for type[]
            //
            Type elementType = underlyingType.GetElementType();
            if (m_writing)
            {
                object arrayValue = (prop != null) ? prop.GetValue(obj, null) : field.GetValue(obj);
                SerializeOut_array(elementType, arrayValue as Array);
            }
            else
            {
                Array arrayValue = SerializeIn_array(elementType);
                if (typeof(TObject).IsValueType)
                {
                    object objBoxed = obj;
                    if (prop != null)
                    {
                        prop.SetValue(objBoxed, arrayValue, null);
                    }
                    else
                    {
                        field.SetValue(objBoxed, arrayValue);
                    }
                    obj = (TObject)objBoxed;
                }
                else
                {
                    if (prop != null)
                    {
                        prop.SetValue(obj, arrayValue, null);
                    }
                    else
                    {
                        field.SetValue(obj, arrayValue);
                    }
                }
            }
            return;
        }

        if (underlyingType.IsEnum)
        {
            //
            // Special case handling for enums
            //
            if (m_writing)
            {
                object enumValue = (prop != null) ? prop.GetValue(obj, null) : field.GetValue(obj);
                SerializeOut_int32(Convert.ToInt32(enumValue));
            }
            else
            {
                Int32 intVal = SerializeIn_int32();
                if (typeof(TObject).IsValueType)
                {
                    object objBoxed = obj;
                    if (prop != null)
                    {
                        prop.SetValue(objBoxed, Enum.ToObject(underlyingType, intVal), null);
                    }
                    else
                    {
                        field.SetValue(objBoxed, Enum.ToObject(underlyingType, intVal));
                    }
                    obj = (TObject)objBoxed;
                }
                else
                {
                    if (prop != null)
                    {
                        prop.SetValue(obj, Enum.ToObject(underlyingType, intVal), null);
                    }
                    else
                    {
                        field.SetValue(obj, Enum.ToObject(underlyingType, intVal));
                    }
                }
            }
            return;
        }

        System.Reflection.MethodInfo baseTypeMethod;
        if (m_serializeBaseTypeMethodLookup.TryGetValue(underlyingType, out baseTypeMethod))
        {
            //
            // Fundamental/base type
            //
            if (m_writing)
            {
                object val = (prop != null) ? prop.GetValue(obj, null) : field.GetValue(obj);
                baseTypeMethod.Invoke(this, new object[1] {
                    val
                });
            }
            else
            {
                object val = baseTypeMethod.Invoke(this, null);
                if (typeof(TObject).IsValueType)
                {
                    object objBoxed = obj;
                    if (prop != null)
                    {
                        prop.SetValue(objBoxed, val, null);
                    }
                    else
                    {
                        field.SetValue(objBoxed, val);
                    }
                    obj = (TObject)objBoxed;
                }
                else
                {
                    if (prop != null)
                    {
                        prop.SetValue(obj, val, null);
                    }
                    else
                    {
                        field.SetValue(obj, val);
                    }
                }
            }
            return;
        }

        // Fallback to the generic object
        if (m_writing)
        {
            object val = (prop != null) ? prop.GetValue(obj, null) : field.GetValue(obj);
            SerializeOut_object(val);
        }
        else
        {
            // Construct the object
            object inValue = SerializeIn_object(underlyingType);
            if (typeof(TObject).IsValueType)
            {
                object objBoxed = obj;
                if (prop != null)
                {
                    prop.SetValue(objBoxed, inValue, null);
                }
                else
                {
                    field.SetValue(objBoxed, inValue);
                }
                obj = (TObject)objBoxed;
            }
            else
            {
                if (prop != null)
                {
                    prop.SetValue(obj, inValue, null);
                }
                else
                {
                    field.SetValue(obj, inValue);
                }
            }
        }
    }
Esempio n. 25
0
    // Try and get game view size
    // Will return true if it is able to work this out
    // If width / height == 0, it means the user has selected an aspect ratio "Resolution"
    public static bool Editor__GetGameViewSize(out float width, out float height, out float aspect)
    {
        try {
            Editor__gameViewReflectionError = false;

            System.Type gameViewType = System.Type.GetType("UnityEditor.GameView,UnityEditor");
            System.Reflection.MethodInfo GetMainGameView = gameViewType.GetMethod("GetMainGameView", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic);
            object mainGameViewInst = GetMainGameView.Invoke(null, null);
            if (mainGameViewInst == null)
            {
                width = height = aspect = 0;
                return(false);
            }
            System.Reflection.FieldInfo s_viewModeResolutions = gameViewType.GetField("s_viewModeResolutions", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic);
            if (s_viewModeResolutions == null)
            {
                System.Reflection.PropertyInfo currentGameViewSize = gameViewType.GetProperty("currentGameViewSize", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic);
                object      gameViewSize     = currentGameViewSize.GetValue(mainGameViewInst, null);
                System.Type gameViewSizeType = gameViewSize.GetType();
                int         gvWidth          = (int)gameViewSizeType.GetProperty("width").GetValue(gameViewSize, null);
                int         gvHeight         = (int)gameViewSizeType.GetProperty("height").GetValue(gameViewSize, null);
                int         gvSizeType       = (int)gameViewSizeType.GetProperty("sizeType").GetValue(gameViewSize, null);
                if (gvWidth == 0 || gvHeight == 0)
                {
                    width = height = aspect = 0;
                    return(false);
                }
                else if (gvSizeType == 0)
                {
                    width  = height = 0;
                    aspect = (float)gvWidth / (float)gvHeight;
                    return(true);
                }
                else
                {
                    width  = gvWidth; height = gvHeight;
                    aspect = (float)gvWidth / (float)gvHeight;
                    return(true);
                }
            }
            else
            {
                Vector2[] viewModeResolutions = (Vector2[])s_viewModeResolutions.GetValue(null);
                float[]   viewModeAspects     = (float[])gameViewType.GetField("s_viewModeAspects", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic).GetValue(null);
                string[]  viewModeStrings     = (string[])gameViewType.GetField("s_viewModeAspectStrings", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic).GetValue(null);
                if (mainGameViewInst != null &&
                    viewModeStrings != null &&
                    viewModeResolutions != null && viewModeAspects != null)
                {
                    int    aspectRatio        = (int)gameViewType.GetField("m_AspectRatio", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic).GetValue(mainGameViewInst);
                    string thisViewModeString = viewModeStrings[aspectRatio];
                    if (thisViewModeString.Contains("Standalone"))
                    {
                        width  = UnityEditor.PlayerSettings.defaultScreenWidth; height = UnityEditor.PlayerSettings.defaultScreenHeight;
                        aspect = width / height;
                    }
                    else if (thisViewModeString.Contains("Web"))
                    {
                        width  = UnityEditor.PlayerSettings.defaultWebScreenWidth; height = UnityEditor.PlayerSettings.defaultWebScreenHeight;
                        aspect = width / height;
                    }
                    else
                    {
                        width  = viewModeResolutions[aspectRatio].x; height = viewModeResolutions[aspectRatio].y;
                        aspect = viewModeAspects[aspectRatio];
                        // this is an error state
                        if (width == 0 && height == 0 && aspect == 0)
                        {
                            return(false);
                        }
                    }
                    return(true);
                }
            }
        }
        catch (System.Exception e) {
            if (Editor__getGameViewSizeError == false)
            {
                Debug.LogError("tk2dCamera.GetGameViewSize - has a Unity update broken this?\nThis is not a fatal error, but a warning that you've probably not got the latest 2D Toolkit update.\n\n" + e.ToString());
                Editor__getGameViewSizeError = true;
            }
            Editor__gameViewReflectionError = true;
        }
        width = height = aspect = 0;
        return(false);
    }
    public static void FacebookSettings()
    {
        EditorGUILayout.Space();
        EditorGUILayout.HelpBox("Facebook Settings", MessageType.None);



        if (!Instalation.IsFacebookInstalled)
        {
            EditorGUILayout.Space();
            EditorGUILayout.HelpBox("Facebook SDK is not found in your project. However you can steel use the device native sharing API.", MessageType.Info);


            return;
        }

        string FBAppId   = "0";
        string FBAppName = "App Name";
        object instance  = null;

        System.Reflection.MethodInfo idSetter    = null;
        System.Reflection.MethodInfo labelSetter = null;

        List <string> ids    = null;
        List <string> labels = null;

        try {
            ScriptableObject FB_Resourse = Resources.Load("FacebookSettings") as ScriptableObject;

            if (FB_Resourse != null)
            {
                Type fb_settings = FB_Resourse.GetType();

                if (SA.Common.Config.FB_SDK_MajorVersionCode == 6)
                {
                    System.Reflection.PropertyInfo propert = fb_settings.GetProperty("AppId", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public);
                    FBAppId = (string)propert.GetValue(null, null);

                    System.Reflection.PropertyInfo Instance = fb_settings.GetProperty("Instance", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic);
                    instance = Instance.GetValue(null, null);

                    System.Reflection.PropertyInfo appLabelsProperty = fb_settings.GetProperty("AppLabels", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public);
                    string[] appLabels = (string[])appLabelsProperty.GetValue(instance, null);

                    if (appLabels.Length >= 1)
                    {
                        FBAppName = appLabels[0];
                    }

                    idSetter    = fb_settings.GetMethod("SetAppId", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public);
                    labelSetter = fb_settings.GetMethod("SetAppLabel", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public);
                }
                else if (SA.Common.Config.FB_SDK_MajorVersionCode == 7)
                {
                    System.Reflection.PropertyInfo idsProperty = fb_settings.GetProperty("AppIds", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public);
                    ids = (List <string>)idsProperty.GetValue(null, null);
                    if (ids.Count >= 1)
                    {
                        FBAppId = ids[0];
                    }

                    System.Reflection.PropertyInfo labelsProperty = fb_settings.GetProperty("AppLabels", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public);
                    labels = (List <string>)labelsProperty.GetValue(null, null);
                    if (labels.Count >= 1)
                    {
                        FBAppName = labels[0];
                    }
                }
            }
        } catch (Exception ex) {
            Debug.LogError("AndroidNative. FBSettings.AppId reflection failed: " + ex.Message);
        }

        EditorGUILayout.BeginHorizontal();
        EditorGUILayout.LabelField("App Name:");
        EditorGUI.BeginChangeCheck();
        string newName = EditorGUILayout.TextField(FBAppName);

        EditorGUILayout.EndHorizontal();

        if (EditorGUI.EndChangeCheck())
        {
            if (SA.Common.Config.FB_SDK_MajorVersionCode == 6)
            {
                if (labelSetter != null && instance != null)
                {
                    labelSetter.Invoke(instance, new object[] { 0, newName });
                }
            }
            else if (SA.Common.Config.FB_SDK_MajorVersionCode == 7)
            {
                if (labels.Count >= 1)
                {
                    labels[0] = newName;
                }
            }
        }

        EditorGUILayout.BeginHorizontal();
        EditorGUILayout.LabelField("App ID:");
        EditorGUI.BeginChangeCheck();
        string newId = EditorGUILayout.TextField(FBAppId);

        EditorGUILayout.EndHorizontal();
        EditorGUILayout.Space();

        if (EditorGUI.EndChangeCheck())
        {
            if (SA.Common.Config.FB_SDK_MajorVersionCode == 6)
            {
                if (idSetter != null && instance != null)
                {
                    idSetter.Invoke(instance, new object[] { 0, newId });
                }
            }
            else if (SA.Common.Config.FB_SDK_MajorVersionCode == 7)
            {
                if (ids.Count >= 1)
                {
                    ids[0] = newId;
                }
            }
        }

        if (SocialPlatfromSettings.Instance.fb_scopes_list.Count == 0)
        {
            SocialPlatfromSettings.Instance.AddDefaultScopes();
        }

        SocialPlatfromSettings.Instance.showPermitions = EditorGUILayout.Foldout(SocialPlatfromSettings.Instance.showPermitions, "Facebook Permissions");
        if (SocialPlatfromSettings.Instance.showPermitions)
        {
            foreach (string s in SocialPlatfromSettings.Instance.fb_scopes_list)
            {
                EditorGUILayout.BeginVertical(GUI.skin.box);
                EditorGUILayout.BeginHorizontal();

                EditorGUILayout.SelectableLabel(s, GUILayout.Height(16));

                if (GUILayout.Button("x", GUILayout.Width(20)))
                {
                    SocialPlatfromSettings.Instance.fb_scopes_list.Remove(s);
                    return;
                }
                EditorGUILayout.EndHorizontal();

                EditorGUILayout.EndVertical();
            }


            EditorGUILayout.BeginHorizontal();
            EditorGUILayout.LabelField("Add new permition: ");
            newPermition = EditorGUILayout.TextField(newPermition);


            EditorGUILayout.EndHorizontal();



            EditorGUILayout.BeginHorizontal();

            EditorGUILayout.Space();
            if (GUILayout.Button("Documentation", GUILayout.Width(100)))
            {
                Application.OpenURL("https://developers.facebook.com/docs/facebook-login/permissions/v2.0");
            }



            if (GUILayout.Button("Add", GUILayout.Width(100)))
            {
                if (newPermition != string.Empty)
                {
                    newPermition = newPermition.Trim();
                    if (!SocialPlatfromSettings.Instance.fb_scopes_list.Contains(newPermition))
                    {
                        SocialPlatfromSettings.Instance.fb_scopes_list.Add(newPermition);
                    }

                    newPermition = string.Empty;
                }
            }
            EditorGUILayout.EndHorizontal();
        }
    }
    // 反射实现深拷贝
    public static object DeepCopyByReflection(object obj)
    {
        if (obj == null)
        {
            return(null);
        }

        System.Object targetObj;
        Type          targetType = obj.GetType();

        // 对于值类型,直接使用=即可
        if (targetType.IsValueType == true)
        {
            targetObj = obj;
        }
        else
        {
            // 对于引用类型
            // 根据targetType创建引用对象
            targetObj = System.Activator.CreateInstance(targetType);
            // 使用反射获取targetType下所有的成员
            System.Reflection.MemberInfo[] memberInfos = obj.GetType().GetMembers();

            // 遍历所有的成员
            foreach (System.Reflection.MemberInfo member in memberInfos)
            {
                // 如果成员为字段类型:获取obj中该字段的值。
                if (member.MemberType == System.Reflection.MemberTypes.Field)
                {
                    System.Reflection.FieldInfo fieldInfo = (System.Reflection.FieldInfo)member;
                    System.Object fieldValue = fieldInfo.GetValue(obj);

                    //如果该值可直接Clone,则直接Clone;否则,递归调用DeepCopyByReflection(该值)。
                    if (fieldValue is ICloneable)
                    {
                        fieldInfo.SetValue(targetObj, (fieldValue as ICloneable).Clone());
                    }
                    else
                    {
                        fieldInfo.SetValue(targetObj, DeepCopyByReflection(fieldValue));
                    }
                }
                // 如果成员为属性类型:获取obj中该属性的值。
                else if (member.MemberType == System.Reflection.MemberTypes.Property)
                {
                    System.Reflection.PropertyInfo propertyInfo = (System.Reflection.PropertyInfo)member;

                    // GetSetMethod(nonPublic) nonPublic means: sIndicates whether the accessor should be returned if it is non-public. true if a non-public accessor is to be returned; otherwise, false.
                    System.Reflection.MethodInfo methodInfo = propertyInfo.GetSetMethod(false);

                    if (methodInfo != null)
                    {
                        try {
                            // 如果该值可直接CLone,则直接Clone;否则,递归调用DeepCopyByReflection(该值)。
                            object propertyValue = propertyInfo.GetValue(obj, null);
                            if (propertyValue is ICloneable)
                            {
                                propertyInfo.SetValue(targetObj, (propertyValue as ICloneable).Clone(), null);
                            }
                            else
                            {
                                propertyInfo.SetValue(targetObj, DeepCopyByReflection(propertyValue), null);
                            }
                        } catch (Exception e) {
                            // some thing except.
                            Debug.Log(e.Message);
                        }
                    }
                }
            }
        }

        return(targetObj);
    }
Esempio n. 28
0
 /// <summary>
 /// ソートレイヤーID取得
 /// </summary>
 public int[] GetSortingLayerUniqueIDs()
 {
     System.Type internalEditorUtilityType = typeof(UnityEditorInternal.InternalEditorUtility);
     System.Reflection.PropertyInfo sortingLayerUniqueIDsProperty = internalEditorUtilityType.GetProperty("sortingLayerUniqueIDs", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic);
     return((int[])sortingLayerUniqueIDsProperty.GetValue(null, null));
 }
Esempio n. 29
0
    private void ExportData(ExportDto dto)
    {
        if (string.IsNullOrEmpty(dto.CurrentConfig.DataPath))
        {
            if (EditorUtility.DisplayDialog(LanguageUtils.CommonSaveFailed, LanguageUtils.ExportNotFound, "OK"))
            {
                return;
            }
        }
        string path = EditorUtility.SaveFilePanel(LanguageUtils.ExportFile, "", dto.CurrentConfig.TableName + ".txt", "txt");

        if (string.IsNullOrEmpty(path))
        {
            if (EditorUtility.DisplayDialog(LanguageUtils.CommonSaveFailed, LanguageUtils.CommonNullPath, "OK"))
            {
                return;
            }
        }
        StringBuilder sb = new StringBuilder();

        for (int i = 0; i < dto.CurrentConfig.FieldList.Count; i++)
        {
            if (dto.CurrentConfig.FieldList[i].IsExport)
            {
                sb.Append(dto.CurrentConfig.FieldList[i].FieldName);
            }
            sb.Append("\t");
        }
        sb.Append("\r\n");
        ScriptableObject assetObj = AssetDatabase.LoadAssetAtPath <ScriptableObject>(dto.CurrentConfig.DataPath);
        object           items    = assetObj.GetType().GetField("DataList").GetValue(assetObj);

        if (items != null)
        {
            int count = (int)items.GetType().GetProperty("Count").GetValue(items, null);
            System.Reflection.PropertyInfo property = items.GetType().GetProperty("Item");
            for (int j = 0; j < count; j++)
            {
                object o = property.GetValue(items, new object[] { j });
                for (int i = 0; i < dto.CurrentConfig.FieldList.Count; i++)
                {
                    if (dto.CurrentConfig.FieldList[i].IsExport)
                    {
                        string str = "";
                        object obj = o.GetType().GetField(dto.CurrentConfig.FieldList[i].FieldName).GetValue(o);

                        GetString(dto.CurrentConfig.FieldList[i].FieldType, obj, ref str);


                        sb.Append(str);
                    }
                    sb.Append("\t");
                }
                sb.Append("\r\n");
            }
        }
        if (!File.Exists(path))
        {
            File.Create(path).Dispose();
        }
        File.WriteAllText(path, sb.ToString());
        EditorUtility.DisplayDialog(LanguageUtils.ExportHead, "Success", "Ok");
    }
Esempio n. 30
0
    public static void SectorizeTerrain(Terrain terrain, int sectorsWidth, int sectorsLength, int sectorsHeight, bool splitTerrain, bool createPortalGeo, bool includeStatic, bool includeDynamic)
    {
        if (!terrain)
        {
            Debug.LogWarning("Cannot sectorize null terrain.");
            return;
        }

        if (terrain.transform.root.GetComponentsInChildren <SECTR_Sector>().Length > 0)
        {
            Debug.LogWarning("Cannot sectorize terrain that is already part of a Sector.");
        }

        string undoString = "Sectorized " + terrain.name;

        if (sectorsWidth == 1 && sectorsLength == 1)
        {
            SECTR_Sector newSector = terrain.gameObject.AddComponent <SECTR_Sector>();
            SECTR_Undo.Created(newSector, undoString);
            newSector.ForceUpdate(true);
            return;
        }

        if (splitTerrain && (!Mathf.IsPowerOfTwo(sectorsWidth) || !Mathf.IsPowerOfTwo(sectorsLength)))
        {
            Debug.LogWarning("Splitting terrain requires power of two sectors in width and length.");
            splitTerrain = false;
        }
        else if (splitTerrain && sectorsWidth != sectorsLength)
        {
            Debug.LogWarning("Splitting terrain requires same number of sectors in width and length.");
            splitTerrain = false;
        }

        int     terrainLayer = terrain.gameObject.layer;
        Vector3 terrainSize  = terrain.terrainData.size;
        float   sectorWidth  = terrainSize.x / sectorsWidth;
        float   sectorHeight = terrainSize.y / sectorsHeight;
        float   sectorLength = terrainSize.z / sectorsLength;

        int heightmapWidth  = (terrain.terrainData.heightmapWidth / sectorsWidth);
        int heightmapLength = (terrain.terrainData.heightmapHeight / sectorsLength);
        int alphaWidth      = terrain.terrainData.alphamapWidth / sectorsWidth;
        int alphaLength     = terrain.terrainData.alphamapHeight / sectorsLength;
        int detailWidth     = terrain.terrainData.detailWidth / sectorsWidth;
        int detailLength    = terrain.terrainData.detailHeight / sectorsLength;

        string sceneDir     = "";
        string sceneName    = "";
        string exportFolder = splitTerrain ? SECTR_Asset.MakeExportFolder("TerrainSplits", false, out sceneDir, out sceneName) : "";

        Transform baseTransform = null;

        if (splitTerrain)
        {
            GameObject baseObject = new GameObject(terrain.name);
            baseTransform = baseObject.transform;
            SECTR_Undo.Created(baseObject, undoString);
        }

        List <Transform> rootTransforms = new List <Transform>();
        List <Bounds>    rootBounds     = new List <Bounds>();

        _GetRoots(includeStatic, includeDynamic, rootTransforms, rootBounds);

        // Create Sectors
        string progressTitle   = "Sectorizing Terrain";
        int    progressCounter = 0;

        EditorUtility.DisplayProgressBar(progressTitle, "Preparing", 0);

        SECTR_Sector[,,] newSectors = new SECTR_Sector[sectorsWidth, sectorsLength, sectorsHeight];
        Terrain[,] newTerrains      = splitTerrain ? new Terrain[sectorsWidth, sectorsLength] : null;
        for (int widthIndex = 0; widthIndex < sectorsWidth; ++widthIndex)
        {
            for (int lengthIndex = 0; lengthIndex < sectorsLength; ++lengthIndex)
            {
                for (int heightIndex = 0; heightIndex < sectorsHeight; ++heightIndex)
                {
                    string newName = terrain.name + " " + widthIndex + "-" + lengthIndex + "-" + heightIndex;

                    EditorUtility.DisplayProgressBar(progressTitle, "Creating sector " + newName, progressCounter++ / (float)(sectorsWidth * sectorsLength * sectorsHeight));

                    GameObject newSectorObject = new GameObject("SECTR " + newName + " Sector");
                    newSectorObject.transform.parent = baseTransform;
                    Vector3 sectorCorner = new Vector3(widthIndex * sectorWidth,
                                                       heightIndex * sectorHeight,
                                                       lengthIndex * sectorLength) + terrain.transform.position;
                    newSectorObject.transform.position = sectorCorner;
                    newSectorObject.isStatic           = true;
                    SECTR_Sector newSector = newSectorObject.AddComponent <SECTR_Sector>();
                    newSector.OverrideBounds = !splitTerrain && (sectorsWidth > 1 || sectorsLength > 1);
                    newSector.BoundsOverride = new Bounds(sectorCorner + new Vector3(sectorWidth * 0.5f, sectorHeight * 0.5f, sectorLength * 0.5f),
                                                          new Vector3(sectorWidth, sectorHeight, sectorLength));
                    newSectors[widthIndex, lengthIndex, heightIndex] = newSector;

                    if (splitTerrain && heightIndex == 0)
                    {
                        GameObject newTerrainObject = new GameObject(newName + " Terrain");
                        newTerrainObject.layer                   = terrainLayer;
                        newTerrainObject.tag                     = terrain.tag;
                        newTerrainObject.transform.parent        = newSectorObject.transform;
                        newTerrainObject.transform.localPosition = Vector3.zero;
                        newTerrainObject.transform.localRotation = Quaternion.identity;
                        newTerrainObject.transform.localScale    = Vector3.one;
                        newTerrainObject.isStatic                = true;
                        Terrain newTerrain = newTerrainObject.AddComponent <Terrain>();
                        newTerrain.terrainData = SECTR_Asset.Create <TerrainData>(exportFolder, newName, new TerrainData());
                        EditorUtility.SetDirty(newTerrain.terrainData);
                        SECTR_VC.WaitForVC();

                        // Copy properties
                        // Basic terrain properties
                        newTerrain.editorRenderFlags   = terrain.editorRenderFlags;
                        newTerrain.castShadows         = terrain.castShadows;
                        newTerrain.heightmapMaximumLOD = terrain.heightmapMaximumLOD;
                        newTerrain.heightmapPixelError = terrain.heightmapPixelError;
                        newTerrain.lightmapIndex       = -1;                   // Can't set lightmap UVs on terrain.
                        newTerrain.materialTemplate    = terrain.materialTemplate;
                                                #if !UNITY_4
                        newTerrain.bakeLightProbesForTrees = terrain.bakeLightProbesForTrees;
                        newTerrain.legacyShininess         = terrain.legacyShininess;
                        newTerrain.legacySpecular          = terrain.legacySpecular;
                                                #endif

                        // Copy geometric data
                        int heightmapBaseX  = widthIndex * heightmapWidth;
                        int heightmapBaseY  = lengthIndex * heightmapLength;
                        int heightmapWidthX = heightmapWidth + (sectorsWidth > 1 ? 1 : 0);
                        int heightmapWidthY = heightmapLength + (sectorsLength > 1 ? 1 : 0);
                        newTerrain.terrainData.heightmapResolution = terrain.terrainData.heightmapResolution / sectorsWidth;
                        newTerrain.terrainData.size = new Vector3(sectorWidth, terrainSize.y, sectorLength);
                        newTerrain.terrainData.SetHeights(0, 0, terrain.terrainData.GetHeights(heightmapBaseX, heightmapBaseY, heightmapWidthX, heightmapWidthY));
                                                #if !UNITY_4
                        newTerrain.terrainData.thickness = terrain.terrainData.thickness;
                                                #endif

                        // Copy alpha maps
                        int alphaBaseX = alphaWidth * widthIndex;
                        int alphaBaseY = alphaLength * lengthIndex;
                        newTerrain.terrainData.splatPrototypes    = terrain.terrainData.splatPrototypes;
                        newTerrain.basemapDistance                = terrain.basemapDistance;
                        newTerrain.terrainData.baseMapResolution  = terrain.terrainData.baseMapResolution / sectorsWidth;
                        newTerrain.terrainData.alphamapResolution = terrain.terrainData.alphamapResolution / sectorsWidth;
                        newTerrain.terrainData.SetAlphamaps(0, 0, terrain.terrainData.GetAlphamaps(alphaBaseX, alphaBaseY, alphaWidth, alphaLength));

                        // Copy detail info
                        newTerrain.detailObjectDensity          = terrain.detailObjectDensity;
                        newTerrain.detailObjectDistance         = terrain.detailObjectDistance;
                        newTerrain.terrainData.detailPrototypes = terrain.terrainData.detailPrototypes;
                        newTerrain.terrainData.SetDetailResolution(terrain.terrainData.detailResolution / sectorsWidth, 8);                         // TODO: extract detailResolutionPerPatch
                                                #if !UNITY_4
                        newTerrain.collectDetailPatches = terrain.collectDetailPatches;
                                                #endif

                        int detailBaseX = detailWidth * widthIndex;
                        int detailBaseY = detailLength * lengthIndex;
                        int numLayers   = terrain.terrainData.detailPrototypes.Length;
                        for (int layer = 0; layer < numLayers; ++layer)
                        {
                            newTerrain.terrainData.SetDetailLayer(0, 0, layer, terrain.terrainData.GetDetailLayer(detailBaseX, detailBaseY, detailWidth, detailLength, layer));
                        }

                        // Copy grass and trees
                        newTerrain.terrainData.wavingGrassAmount   = terrain.terrainData.wavingGrassAmount;
                        newTerrain.terrainData.wavingGrassSpeed    = terrain.terrainData.wavingGrassSpeed;
                        newTerrain.terrainData.wavingGrassStrength = terrain.terrainData.wavingGrassStrength;
                        newTerrain.terrainData.wavingGrassTint     = terrain.terrainData.wavingGrassTint;
                        newTerrain.treeBillboardDistance           = terrain.treeBillboardDistance;
                        newTerrain.treeCrossFadeLength             = terrain.treeCrossFadeLength;
                        newTerrain.treeDistance               = terrain.treeDistance;
                        newTerrain.treeMaximumFullLODCount    = terrain.treeMaximumFullLODCount;
                        newTerrain.terrainData.treePrototypes = terrain.terrainData.treePrototypes;
                        newTerrain.terrainData.RefreshPrototypes();

                        foreach (TreeInstance treeInstace in terrain.terrainData.treeInstances)
                        {
                            if (treeInstace.prototypeIndex >= 0 && treeInstace.prototypeIndex < newTerrain.terrainData.treePrototypes.Length &&
                                newTerrain.terrainData.treePrototypes[treeInstace.prototypeIndex].prefab)
                            {
                                Vector3 worldSpaceTreePos = Vector3.Scale(treeInstace.position, terrainSize) + terrain.transform.position;
                                if (newSector.BoundsOverride.Contains(worldSpaceTreePos))
                                {
                                    Vector3 localSpaceTreePos = new Vector3((worldSpaceTreePos.x - newTerrain.transform.position.x) / sectorWidth,
                                                                            treeInstace.position.y,
                                                                            (worldSpaceTreePos.z - newTerrain.transform.position.z) / sectorLength);
                                    TreeInstance newInstance = treeInstace;
                                    newInstance.position = localSpaceTreePos;
                                    newTerrain.AddTreeInstance(newInstance);
                                }
                            }
                        }

                        // Copy physics
                                                #if UNITY_4_LATE
                        newTerrain.terrainData.physicMaterial = terrain.terrainData.physicMaterial;
                                                #endif

                        // Force terrain to rebuild
                        newTerrain.Flush();

                        UnityEditor.EditorUtility.SetDirty(newTerrain.terrainData);
                        SECTR_VC.WaitForVC();
                        newTerrain.enabled = false;
                        newTerrain.enabled = true;

                        TerrainCollider terrainCollider = terrain.GetComponent <TerrainCollider>();
                        if (terrainCollider)
                        {
                            TerrainCollider newCollider = newTerrainObject.AddComponent <TerrainCollider>();
                                                        #if !UNITY_4_LATE
                            newCollider.sharedMaterial = terrainCollider.sharedMaterial;
                                                        #endif
                            newCollider.terrainData = newTerrain.terrainData;
                        }

                        newTerrains[widthIndex, lengthIndex] = newTerrain;
                        SECTR_Undo.Created(newTerrainObject, undoString);
                    }
                    newSector.ForceUpdate(true);
                    SECTR_Undo.Created(newSectorObject, undoString);

                    _Encapsulate(newSector, rootTransforms, rootBounds, undoString);
                }
            }
        }

        // Create portals and neighbors
        progressCounter = 0;
        for (int widthIndex = 0; widthIndex < sectorsWidth; ++widthIndex)
        {
            for (int lengthIndex = 0; lengthIndex < sectorsLength; ++lengthIndex)
            {
                for (int heightIndex = 0; heightIndex < sectorsHeight; ++heightIndex)
                {
                    EditorUtility.DisplayProgressBar(progressTitle, "Creating portals...", progressCounter++ / (float)(sectorsWidth * sectorsLength * sectorsHeight));

                    if (widthIndex < sectorsWidth - 1)
                    {
                        _CreatePortal(createPortalGeo, newSectors[widthIndex + 1, lengthIndex, heightIndex], newSectors[widthIndex, lengthIndex, heightIndex], baseTransform, undoString);
                    }

                    if (lengthIndex < sectorsLength - 1)
                    {
                        _CreatePortal(createPortalGeo, newSectors[widthIndex, lengthIndex + 1, heightIndex], newSectors[widthIndex, lengthIndex, heightIndex], baseTransform, undoString);
                    }

                    if (heightIndex > 0)
                    {
                        _CreatePortal(createPortalGeo, newSectors[widthIndex, lengthIndex, heightIndex], newSectors[widthIndex, lengthIndex, heightIndex - 1], baseTransform, undoString);
                    }
                }
            }
        }

        if (splitTerrain)
        {
            progressCounter = 0;
            for (int widthIndex = 0; widthIndex < sectorsWidth; ++widthIndex)
            {
                for (int lengthIndex = 0; lengthIndex < sectorsLength; ++lengthIndex)
                {
                    EditorUtility.DisplayProgressBar(progressTitle, "Smoothing split terrain...", progressCounter++ / (float)(sectorsWidth * sectorsLength * sectorsHeight));

                    // Blend together the seams of the alpha maps, which requires
                    // going through all of the mip maps of all of the layer textures.
                    // We have to blend here rather than when we set the alpha data (above)
                    // because Unity computes mips and we need to blend all of the mips.
                    Terrain newTerrain = newTerrains[widthIndex, lengthIndex];

                    SECTR_Sector terrainSector = newSectors[widthIndex, lengthIndex, 0];
                    terrainSector.LeftTerrain   = widthIndex > 0 ? newSectors[widthIndex - 1, lengthIndex, 0] : null;
                    terrainSector.RightTerrain  = widthIndex < sectorsWidth - 1 ? newSectors[widthIndex + 1, lengthIndex, 0] : null;
                    terrainSector.BottomTerrain = lengthIndex > 0 ? newSectors[widthIndex, lengthIndex - 1, 0] : null;
                    terrainSector.TopTerrain    = lengthIndex < sectorsLength - 1 ? newSectors[widthIndex, lengthIndex + 1, 0] : null;
                    terrainSector.ConnectTerrainNeighbors();

                    // Use reflection trickery to get at the raw texture values.
                    System.Reflection.PropertyInfo alphamapProperty = newTerrain.terrainData.GetType().GetProperty("alphamapTextures",
                                                                                                                   System.Reflection.BindingFlags.NonPublic |
                                                                                                                   System.Reflection.BindingFlags.Public |
                                                                                                                   System.Reflection.BindingFlags.Instance |
                                                                                                                   System.Reflection.BindingFlags.Static);
                    // Get the texture we'll write into
                    Texture2D[] alphaTextures = (Texture2D[])alphamapProperty.GetValue(newTerrain.terrainData, null);
                    int         numTextures   = alphaTextures.Length;

                    // Get the textures we'll read from
                    Texture2D[] leftNeighborTextures   = terrainSector.LeftTerrain != null ? (Texture2D[])alphamapProperty.GetValue(newTerrains[widthIndex - 1, lengthIndex].terrainData, null) : null;
                    Texture2D[] rightNeighborTextures  = terrainSector.RightTerrain != null ? (Texture2D[])alphamapProperty.GetValue(newTerrains[widthIndex + 1, lengthIndex].terrainData, null) : null;
                    Texture2D[] topNeighborTextures    = terrainSector.TopTerrain != null ? (Texture2D[])alphamapProperty.GetValue(newTerrains[widthIndex, lengthIndex + 1].terrainData, null) : null;
                    Texture2D[] bottomNeighborTextures = terrainSector.BottomTerrain != null ? (Texture2D[])alphamapProperty.GetValue(newTerrains[widthIndex, lengthIndex - 1].terrainData, null) : null;

                    for (int textureIndex = 0; textureIndex < numTextures; ++textureIndex)
                    {
                        Texture2D alphaTexture  = alphaTextures[textureIndex];
                        Texture2D leftTexture   = leftNeighborTextures != null ? leftNeighborTextures[textureIndex] : null;
                        Texture2D rightTexture  = rightNeighborTextures != null ? rightNeighborTextures[textureIndex] : null;
                        Texture2D topTexture    = topNeighborTextures != null ? topNeighborTextures[textureIndex] : null;
                        Texture2D bottomTexture = bottomNeighborTextures != null ? bottomNeighborTextures[textureIndex] : null;
                        int       numMips       = alphaTexture.mipmapCount;
                        for (int mipIndex = 0; mipIndex < numMips; ++mipIndex)
                        {
                            Color[] alphaTexels = alphaTexture.GetPixels(mipIndex);
                            int     width       = (int)Mathf.Sqrt(alphaTexels.Length);
                            int     height      = width;
                            for (int texelWidthIndex = 0; texelWidthIndex < width; ++texelWidthIndex)
                            {
                                for (int texelHeightIndex = 0; texelHeightIndex < height; ++texelHeightIndex)
                                {
                                    // We can take advantage of the build order to average on the leading edges (right and top)
                                    // and then copy form the trailing edges (left and bottom)
                                    if (texelWidthIndex == 0 && leftTexture)
                                    {
                                        Color[] neighborTexels = leftTexture.GetPixels(mipIndex);
                                        alphaTexels[texelWidthIndex + texelHeightIndex * width] = neighborTexels[(width - 1) + (texelHeightIndex * width)];
                                    }
                                    else if (texelWidthIndex == width - 1 && rightTexture)
                                    {
                                        Color[] neighborTexels = rightTexture.GetPixels(mipIndex);
                                        alphaTexels[texelWidthIndex + texelHeightIndex * width] += neighborTexels[0 + (texelHeightIndex * width)];
                                        alphaTexels[texelWidthIndex + texelHeightIndex * width] *= 0.5f;
                                    }
                                    else if (texelHeightIndex == 0 && bottomTexture)
                                    {
                                        Color[] neighborTexels = bottomTexture.GetPixels(mipIndex);
                                        alphaTexels[texelWidthIndex + texelHeightIndex * width] = neighborTexels[texelWidthIndex + ((height - 1) * width)];
                                    }
                                    else if (texelHeightIndex == height - 1 && topTexture)
                                    {
                                        Color[] neighborTexels = topTexture.GetPixels(mipIndex);
                                        alphaTexels[texelWidthIndex + texelHeightIndex * width] += neighborTexels[texelWidthIndex + (0 * width)];
                                        alphaTexels[texelWidthIndex + texelHeightIndex * width] *= 0.5f;
                                    }
                                }
                            }
                            alphaTexture.SetPixels(alphaTexels, mipIndex);
                        }
                        alphaTexture.wrapMode = TextureWrapMode.Clamp;
                        alphaTexture.Apply(false);
                    }

                    newTerrain.Flush();
                }
            }
        }

        EditorUtility.ClearProgressBar();

        // destroy original terrain
        if (splitTerrain)
        {
            SECTR_Undo.Destroy(terrain.gameObject, undoString);
        }
    }
Esempio n. 31
-1
        public static string GetPropertyValue(PropertyInfo propertyInfo, object ob)
        {
            string value = "";
            if (propertyInfo != null)
            {
                if(propertyInfo.PropertyType==typeof(Color))
                {
                    Color color = (Color)(propertyInfo.GetValue(ob, null));
                    value = color.ToArgb().ToString();
                }
                else if(propertyInfo.PropertyType== typeof(Font))
                {
                    Font font = (Font)(propertyInfo.GetValue(ob, null));
                    value = string.Format("{0},{1},{2},{3}", font.Name, font.Size.ToString(), font.Bold?"1":"0", font.Italic?"1":"0");
                }
                else if (propertyInfo.PropertyType == typeof(Image))
                {
                    Image image = (Image)(propertyInfo.GetValue(ob, null));
                    byte[] imageBuffer = Helpers.ImageHelper.ImageToBytes(image);
                    value = System.Convert.ToBase64String(imageBuffer);
                }
                else
                {
                    value = propertyInfo.GetValue(ob, null) == null ? "" : propertyInfo.GetValue(ob, null).ToString();
                }
            }

            return value;
        }
Esempio n. 32
-1
        public override void RepairValue(PropertyInfo prop, object entity)
        {
            ParameterAttribute attr = (ParameterAttribute)prop.GetCustomAttribute((Type)typeof(ParameterAttribute), (bool)false);

            FieldName = prop.Name;

            try
            {
                ValueMin = CastToType(ValueMin);
            }
            catch (Exception)
            {
                ValueMin = null;
            }

            if (ValueMin == null)
                ValueMin = prop.GetValue(entity);

            try
            {
                ValueMax = CastToType(ValueMax);
            }
            catch (Exception)
            {
                ValueMax = null;
            }

            if (ValueMax == null)
                ValueMax = prop.GetValue(entity);

            DisplayName = (attr.Name == null) ? prop.Name : attr.Name;
            Description = (attr.Description == null) ? "" : attr.Description;
            TypeName = prop.PropertyType.FullName;
        }
 private KeyValuePair<string, object> CreateKeyValuePair(object target, PropertyInfo property)
 {
     object value;
     if (property.PropertyType.IsEnum) value = (int) property.GetValue(target, null);
     else value = property.GetValue(target, null);
     return new KeyValuePair<string, object>(property.Name, value);
 }
Esempio n. 34
-1
        public ReadOnlyControl(PropertyInfo prop, IAfterglowPlugin plugin)
            : base(prop, FONT_SIZE)
        {
            ConfigReadOnlyAttribute configAttribute = Attribute.GetCustomAttribute(prop, typeof(ConfigReadOnlyAttribute)) as ConfigReadOnlyAttribute;

            if (configAttribute == null)
            {
                throw new Exception("prop is not a ConfigReadOnlyAttribute");
            }
            //Create value Label
            if (configAttribute.IsHyperlink)
            {
                string link = prop.GetValue(plugin, null).ToString();
                _valueLinkLabel = new LinkLabel();
                _valueLinkLabel.Name = Guid.NewGuid().ToString();
                _valueLinkLabel.Text = link;
                Font font = new Font(_valueLinkLabel.Font.FontFamily, FONT_SIZE);
                _valueLinkLabel.Font = font;
                _valueLinkLabel.Links.Add(0,link.Length,link);
                _valueLinkLabel.LinkClicked += new LinkLabelLinkClickedEventHandler(LinkClicked);
                this.Controls.Add(_valueLinkLabel);
            }
            else
            {
                _valueLabel = new Label();
                _valueLabel.Name = Guid.NewGuid().ToString();
                _valueLabel.Text = prop.GetValue(plugin, null).ToString();
                Font font = new Font(_valueLabel.Font.FontFamily, FONT_SIZE);
                _valueLabel.Font = font;
                this.Controls.Add(_valueLabel);
            }

            InitializeComponent();
        }
			public DBParam(DBConnectInfo.DBType dbType, PropertyInfo prop, DbConnectionStringBuilder values, DbConnectionStringBuilder defaults)
			{
				DBType = dbType;
				Name = prop.Name;
				try { Original = prop.GetValue(values); } catch { }
				try { Default = prop.GetValue(defaults); } catch { }
				Value = Original;
				Type = prop.PropertyType;
			}
        protected static string GetValueByProperty(PropertyInfo property, object entity)
        {
            if (!property.PropertyType.IsPrimitive && !property.PropertyType.Namespace.Contains("System"))
            {

                return property.GetValue(entity).ToString();

            }
            else
                return property.GetValue(entity) == null ? string.Empty : property.GetValue(entity).ToString();
        }
Esempio n. 37
-1
 private static object GetValue(PropertyInfo prop, Agency agency, IDictionary<string, string> codeDict)
 {
     if (prop.PropertyType == typeof(string[]))
     {
         var arr = (string[])prop.GetValue(agency);
         return string.Join("; ", arr.Select(x => codeDict[x]));
     }
     else
     {
         return prop.GetValue(agency);
     }
 }
 private static void AddToList(object dto, List<keyValue> list, PropertyInfo property)
 {
     var propertyValue = property.GetValue(dto, null);
     if (propertyValue != null)
     {
         list.Add(new keyValue()
         {
             name = property.Name.ToLower(),
             value = property.GetValue(dto, null).ToString()
         });
     }
 }
Esempio n. 39
-1
        public static object GetCrossRefAttributeValue(this IDynamicObject item, PropertyInfo propertyInfo)
        {
            if (propertyInfo == null)
            {
                throw new ArgumentNullException("propertyInfo");
            }

            if (item == null)
            {
                throw new ArgumentNullException("item");
            }

            var crossRefAttr = propertyInfo.GetCustomAttributes(typeof(CrossRefFieldAttribute), false).Select(d => d).FirstOrDefault() as CrossRefFieldAttribute;
            if (crossRefAttr == null)
            {
                return Convert.ToString(propertyInfo.GetValue(item), CultureInfo.InvariantCulture);
            }

            var memberProperty = item.GetType().GetProperty(propertyInfo.Name + "Member");
            var memberValue = (IDynamicObject)memberProperty.GetValue(item);

            if (memberValue != null)
            {
                var sourceProp = memberValue.GetType().GetProperty(crossRefAttr.RefFieldName);
                if (sourceProp != null)
                {
                    if (sourceProp.GetCustomAttributes(typeof(ApprovalDefinitionAttribute), false).Any())
                    {
                        return item.GetApprovalDisplayValue(crossRefAttr.RefFieldName);
                    }

                    if (sourceProp.GetCustomAttributes(typeof(IsSwitchToggleAttribute), false).Any())
                    {
                        return item.GetBooleanDisplayValue(crossRefAttr.RefFieldName, sourceProp);
                    }

                    if (sourceProp.GetCustomAttributes(typeof(DateTimeFormatAttribute), false).Any())
                    {
                        return item.GetDateTimeDisplayValue(crossRefAttr.RefFieldName, sourceProp);
                    }

                    if (sourceProp.GetCustomAttributes(typeof(CrossRefFieldAttribute), false).Any())
                    {
                        return GetCrossRefAttributeValue(memberValue, sourceProp);
                    }
                }

                return Convert.ToString(memberValue.GetValueByPropertyName(crossRefAttr.RefFieldName));
            }

            return Convert.ToString(propertyInfo.GetValue(item), CultureInfo.InvariantCulture);
        }
Esempio n. 40
-1
 public virtual Dictionary<string, string> GetParams(object obj, PropertyInfo p) {
     var value = p.GetValue(obj, null);
     if (value == null && this.Required)
         return new Dictionary<string, string>(){
             {this.Name, ""}
         };
     else if (value == null && !this.Required)
         return null;
     else
         return new Dictionary<string, string>(){
             {this.Name, p.GetValue(obj, null).ToString()}
         };
 }
Esempio n. 41
-1
        public object GetProperty(PropertyInfo property)
        {
            object result	= null;
            Type type		= property.PropertyType;

            if (Persistence.Required(type))
            {
                object obj	= this.Read(() => property.GetValue(this.Object, null));
                result		= this.cache.GetPersistent(obj);
            }
            else result = this.Read(() => property.GetValue(this.Object, null));

            return result;
        }
Esempio n. 42
-1
 private static void AddArray(object item, PropertyInfo property, KOModel model, bool observable)
 {
     var listType = GetListType(property.PropertyType);
     if (IsSimpleType(listType))
     {
         dynamic list = property.GetValue(item) ?? new List<object>();
         model.AddArray(ToJavascriptName(property), list, observable);
     }
     else
     {
         var list = property.GetValue(item) as IEnumerable<object> ?? new List<object>();
         model.AddArray(ToJavascriptName(property), list.Select(x => x.ToKO()), observable);
     }
 }
Esempio n. 43
-1
        public SpellCheckProperty(PropertyInfo property, object o, string description)
        {
            this.m_Regex = new System.Text.RegularExpressions.Regex(@"\b\w+\b");
            this.m_CurrentMatchIndex = -1;
            this.m_Property = property;
            this.m_O = o;
            this.m_Description = description;
            string text = string.Empty;

            if (property.GetValue(this.m_O) != null)
            {
                text = (string)property.GetValue(this.m_O);
            }
            this.m_Matches = this.m_Regex.Matches(text);
        }
Esempio n. 44
-1
        private static int GetVersionFromPropertyInfo(object obj, PropertyInfo property)
        {
            var value = property.GetValue(obj, index: null);
            if (value == null)
            {
                return DefaultVersion;
            }

            int? version = GetPropertyVersion(property);
            if (!version.HasValue)
            {
                return DefaultVersion;
            }

            var stringValue = value as string;
            if (stringValue != null)
            {
                if (!string.IsNullOrEmpty(stringValue))
                {
                    return version.Value;
                }

                return DefaultVersion;
            }

            // For all other object types a null check would suffice.
            return version.Value;
        }
        /// <summary>
        /// Validates the value given by the entity and property
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="prop"></param>
        /// <returns></returns>
        public override ValidationResult Validate(DomainEntityBase entity, PropertyInfo prop)
        {
            string v = prop.GetValue(entity, null) as string;
            ValidationResult result = new ValidationResult()
            {
                Entity = entity,
                MemberValue = v,
                Prop = prop,
                Validation = this,
                Level = ValidationLevel.Property
            };

            if (!(v is string))
            {
                result.IsValid = false;
                return result;
            }

            if (Allowed.Contains((string)v, CaseSensitive ? StringComparer.InvariantCulture : StringComparer.InvariantCultureIgnoreCase))
            {
                result.IsValid = true;
                return result;
            }
            else
            {
                result.IsValid = false;

                IEnumerable<string> scores = FuzzyStringMatcher.RankByScore(v, Allowed).Take(3);
                scores = scores.Select(s => "\"" + s + "\"");
                result.Message = String.Format("Possible matches? ({0})", String.Join(", ", scores));
            }

            return result;
        }
Esempio n. 46
-1
        public SetTimeSpanGump( PropertyInfo prop, Mobile mobile, object o, Stack stack, int page, ArrayList list )
            : base(GumpOffsetX, GumpOffsetY)
        {
            m_Property = prop;
            m_Mobile = mobile;
            m_Object = o;
            m_Stack = stack;
            m_Page = page;
            m_List = list;

            TimeSpan ts = (TimeSpan)prop.GetValue( o, null );

            AddPage( 0 );

            AddBackground( 0, 0, BackWidth, BackHeight, BackGumpID );
            AddImageTiled( BorderSize, BorderSize, TotalWidth - (OldStyle ? SetWidth + OffsetSize : 0), TotalHeight, OffsetGumpID );

            AddRect( 0, prop.Name, 0, -1 );
            AddRect( 1, ts.ToString(), 0, -1 );
            AddRect( 2, "Zero", 1, -1 );
            AddRect( 3, "From H:M:S", 2, -1 );
            AddRect( 4, "H:", 3, 0 );
            AddRect( 5, "M:", 4, 1 );
            AddRect( 6, "S:", 5, 2 );
        }
Esempio n. 47
-1
 public ObjectMeta(PropertyInfo property, object obj)
 {
     Type = property.PropertyType;
     Value = property.GetValue(obj, new object[0]);
     Name = property.Name;
     DisplayName = GetDisplayName();
 }
        /// <summary>
        /// Gets the value.
        /// </summary>
        /// <param name="propertyInfo">The property info.</param>
        /// <returns></returns>
        private BsonPropertyValue GetValue(PropertyInfo propertyInfo)
        {
            Type type = null;
            var value = propertyInfo.GetValue(_example, null);
            if (value != null && typeof(Code).IsAssignableFrom(value.GetType()))
            {
                Code code = (Code)value;
                code.Value = TranslateJavascript(code.Value);
                return new BsonPropertyValue(typeof(Code), code, false);
            }

            bool isDictionary = false;
            var memberMap = GetAliasFromMemberName(propertyInfo.Name).MemberMap;
            if (memberMap != null)
            {
                if (memberMap is CollectionMemberMap)
                    type = ((CollectionMemberMap)memberMap).ElementType;
                else if (memberMap is DictionaryMemberMap)
                {
                    type = ((DictionaryMemberMap)memberMap).ValueType;
                    isDictionary = true;
                }

                if (type == null || type == typeof(object))
                    type = memberMap.MemberReturnType;
            }
            else
                type = propertyInfo.PropertyType;

            return new BsonPropertyValue(type, value, isDictionary);
        }
Esempio n. 49
-1
 private void SerializeProperty(XElement xmlSection, PropertyInfo item, IConfigSection section)
 {
     if (item.PropertyType.Name == "ObservableCollection`1")
     {
         var xmlProperty = new XElement("item", new XAttribute("key", item.Name));
         var list = (IEnumerable<string>)item.GetValue(section, null);
         AddValueToProperty(xmlProperty, string.Join(";", list));
         xmlSection.Add(xmlProperty);
     }
     else
     {
         var xmlProperty = new XElement("item", new XAttribute("key", item.Name));
         AddValueToProperty(xmlProperty, item.GetValue(section, null).ToString());
         xmlSection.Add(xmlProperty);
     }
 }
        /// <summary>
        /// Traverses the property graph of an object and returns the property at the end of the expression.
        /// </summary>
        /// <param name="graph">The object graph to use. Must not be null.</param>
        /// <param name="expression">The expression of the property. Must not be empty.</param>
        /// <param name="throwOnMissing">Whether or not to throw an exception if any property in the expression did not exist.</param>
        /// <param name="property">If the return value is <c>true</c>, this parameter contains the property that was found.</param>
        /// <param name="target">If the return value is <c>true</c>, this parameter contains the instance of the object on which the property was found.</param>
        /// <returns>Whether or not the property could be found.</returns>
        /// <exception cref="System.MissingFieldException">A certain property in the expression was not found.</exception>
        public static bool GetPropertyFromExpression(object graph, string expression, bool throwOnMissing, out PropertyInfo property, out object target)
        {
            string[] tokens = expression.Split(new[] { '.' });

            target = graph;
            property = null;
            for (int i = 0; i < tokens.Length; i++)
            {
                string propertyName = tokens[i];

                property = target.GetType().GetProperty(propertyName);
                if (property == null)
                {
                    if (throwOnMissing)
                    {
                        string message = string.Format("Property with name '{0}' was not found in object type '{1}' (expression was '{2}').", propertyName, target.GetType().Name, expression);
                        throw new MissingFieldException(target.GetType().Name, propertyName);
                    }
                    return false;
                }

                if (i < tokens.Length - 1)
                {
                    // Next iteration... step down one hierarchy level
                    target = property.GetValue(target, null);
                }
            }

            return true;
        }
        public GetSetGeneric(PropertyInfo info)
        {
            Name = info.Name;
            Info = info;
            CollectionType = Info.PropertyType.GetInterface ("IEnumerable", true) != null;
            var getMethod = info.GetGetMethod (true);
            var setMethod = info.GetSetMethod (true);
            if(getMethod == null)
            {

                Get = (o)=> {
                    return info.GetValue(o, null);
                };
                Set = (o,v) => {
                    info.SetValue(o, v, null);
                };
                return;
            }
            Get = (o) => {
                    return getMethod.Invoke (o, null);
            };
            Set = (o,v) => {
                try {
                    setMethod.Invoke (o, new [] {v});
                } catch (Exception e) {
                    Radical.LogWarning (string.Format("When setting {0} to {1} found {2}:", o.ToString(), v.ToString(), e.ToString ()));
                }
            };
        }
 public static object GetProperty(object SourceObject, string PropertyPath, out PropertyInfo PropertyInfo)
 {
     try
     {
         if (SourceObject == null)
         {
             throw new NullReferenceException("System assign value fails since it is trying to assign value to null object.");                    
         }
         string[] Splitter = { "." };
         string[] SourceProperties = PropertyPath.Split(Splitter, StringSplitOptions.None);
         object TempSourceProperty = SourceObject;
         Type PropertyType = SourceObject.GetType();
         PropertyInfo = GetPropertyInfoFromSinglePath(PropertyType, SourceProperties[0]);
         PropertyType = PropertyInfo.PropertyType;
         for (int x = 1; x < SourceProperties.Length; ++x)
         {
             if (TempSourceProperty != null)
             {
                 TempSourceProperty = PropertyInfo.GetValue(TempSourceProperty, null);
             }
             PropertyInfo = GetPropertyInfoFromSinglePath(PropertyType, SourceProperties[x]);
             PropertyType = PropertyInfo.PropertyType;
         }
         return TempSourceProperty;
     }
     catch { throw; }
 }
        public void PropertyGetsCorrectDefaultValueUponConstruction(Type type, PropertyInfo property)
        {
            object original;
            try
            {
                try
                {
                    original = CreateInstance(type);
                }
                catch (TargetInvocationException ex)
                {
                    throw ex.InnerException;
                }
            }
            catch (NotSupportedException)
            {
                return;
            }
            object defaultPropertyValue = property.GetValue(original, null);

            var attr = property.GetCustomAttributes(typeof(DefaultValueAttribute), true).FirstOrDefault() as DefaultValueAttribute;
            if (attr == null)
                return; // another unit-test fails on this
            object expectedPropertyValue = attr.Value;
            Assert.That(defaultPropertyValue, Is.EqualTo(expectedPropertyValue));
        }
        protected override void ValidateProperty(ITag tag, PropertyInfo propertyInfo)
        {
            if (tag == null || propertyInfo == null)
                return;

            var enumType = propertyInfo.GetCustomAttribute<EnumProperyTypeAttribute>();
            if (enumType == null)
                return;

            var value = propertyInfo.GetValue(tag) as ITagAttribute;
            if (!(value?.IsConstant ?? false))
                return;

            var enumValues = enumType.EnumValues.Cast<object>().Select(v => v.ToString().ToLowerInvariant()).ToList();

            var text = value.ConstantValue.ToString();
            var names = enumType.Multiple ? text.Split(enumType.Separator) : new[] { text };
            foreach (var name in names.Select(n => n?.Trim()))
            {
                if (name == enumType.Wildcard)
                    continue;

                if (!enumValues.Contains(name.ToLowerInvariant()))
                    throw InvalidValueException(name, enumType.EnumValues);
            }
        }
Esempio n. 55
-1
        public static string GetItemKey(PropertyInfo getKeyMethod, TransactionInfo data)
        {
            object value = getKeyMethod.GetValue(data, null);
            string itemKey = (value == null ? string.Empty : value.ToString());

            return itemKey;
        }
Esempio n. 56
-1
        public static void BindFinalValue(PropertyInfo property, object parentItem, object value, XObject sourceXObject, bool definition)
        {
            sourceXObject.AddAnnotation(value);
            Type propertyType = property.PropertyType;

            if (CommonUtility.IsContainerOf(typeof(ICollection<object>), propertyType) && propertyType.GetGenericArguments()[0].IsAssignableFrom(value.GetType()))
            {
                object collection = property.GetValue(parentItem, null);
                MethodInfo addMethod = collection.GetType().GetMethod("Add");
                addMethod.Invoke(collection, new[] { value });
            }
            else if (propertyType.IsAssignableFrom(value.GetType()))
            {
                property.SetValue(parentItem, value, null);
            }
            else
            {
                // TODO: Message.Error("No Binding Mechanism Worked");
            }

            var mappingProvider = value as IXObjectMappingProvider;
            if (mappingProvider != null && definition)
            {
                mappingProvider.BoundXObject = new XObjectMapping(sourceXObject, property.Name);
            }
        }
Esempio n. 57
-1
 public PropertyDefinition(PropertyInfo property)
 {
     Info = property;
     Name = property.Name;
     PropertyType = property.PropertyType;
     Attributes = property.GetCustomAttributes(true);
     foreach (var a in Attributes)
     {
         if (a is IUniquelyNamed)
             (a as IUniquelyNamed).Name = Name;
     }
     Getter = (instance) => Info.GetValue(instance, null);
     Setter = (instance, value) => Info.SetValue(instance, value, null);
     Editable = Attributes.OfType<IEditable>().FirstOrDefault();
     Displayable = Attributes.OfType<IDisplayable>().FirstOrDefault();
     Persistable = Attributes.OfType<IPersistableProperty>().FirstOrDefault()
         ?? new PersistableAttribute 
         { 
             PersistAs = property.DeclaringType == typeof(ContentItem)
                 ? PropertyPersistenceLocation.Column
                 : Editable != null
                     ? PropertyPersistenceLocation.Detail
                     : PropertyPersistenceLocation.Ignore
         };
     DefaultValue = Attributes.OfType<IInterceptableProperty>().Select(ip => ip.DefaultValue).Where(v => v != null).FirstOrDefault();
 }
Esempio n. 58
-1
        public static void UpdateCollectionIds(string className, int id, PropertyInfo propertyInfo, object o,
                                            Func<Type, int> iDCreator)
        {
            var collection = propertyInfo.GetValue(o, null) as IEnumerable;
            foreach (var item in collection)
            {
                var prop = item.GetType().GetProperties().FirstOrDefault(x => x.Name == className + "Id");
                if (prop != null)
                {
                    prop.SetValue(item, id, null);
                }
                var vitem = item as IValueClass;
                if (vitem != null)
                {
                    var type = vitem.GetType();
                    if (vitem.Id == 0) vitem.Id = iDCreator(type);
                    type.GetProperties()
                        .Where(
                            x =>
                            x.PropertyType.IsGenericType &&
                            x.PropertyType.GetInterfaces().Contains(typeof(IEnumerable)))
                        .ToList().ForEach(x => UpdateCollectionIds(type.Name, vitem.Id, x, item, iDCreator));
                }

            }
        }
		public SetDateTimeGump(PropertyInfo prop, Mobile mobile, object o, Stack stack, int page, ArrayList list)
			: base(GumpOffsetX, GumpOffsetY)
		{
			m_Property = prop;
			m_Mobile = mobile;
			m_Object = o;
			m_Stack = stack;
			m_Page = page;
			m_List = list;

			m_OldDT = (DateTime)prop.GetValue(o, null);

			AddPage(0);

			AddBackground(0, 0, BackWidth, BackHeight, BackGumpID);
			AddImageTiled(BorderSize, BorderSize, TotalWidth - (OldStyle ? SetWidth + OffsetSize : 0), TotalHeight, OffsetGumpID);

			AddRect(0, prop.Name, 0, -1);
			AddRect(1, String.Format("{0:u}", m_OldDT), 0, -1);
			AddRect(2, "MinValue", 1, -1);
			AddRect(3, "From YYYY:MM:DD hh:mm", 2, -1);
			AddRect(4, "From YYYY:MM:DD", 3, -1);
			AddRect(5, "From hh:mm", 4, -1);
			AddRect(6, "Year:", 5, 0);
			AddRect(7, "Month:", 6, 1);
			AddRect(8, "Day:", 7, 2);
			AddRect(9, "Hour:", 8, 3);
			AddRect(10, "Minute:", 9, 4);
			AddRect(11, "MaxValue", 10, -1);
		}