System.Array.GetValue(int)

Here are the examples of the csharp api System.Array.GetValue(int) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

773 Examples 7

19 View Source File : RandomHelper.cs
License : MIT License
Project Creator : 1996v

public static object RandomValue(this Type t, bool stringValueAllowEmpty = true)
        {
            if (t.IsPrimitive)
            {
                if (t == typeof(byte))
                {
                    return (byte)(Rand.Next(byte.MaxValue - byte.MinValue + 1) + byte.MinValue);
                }

                if (t == typeof(sbyte))
                {
                    return (sbyte)(Rand.Next(sbyte.MaxValue - sbyte.MinValue + 1) + sbyte.MinValue);
                }

                if (t == typeof(short))
                {
                    return (short)(Rand.Next(short.MaxValue - short.MinValue + 1) + short.MinValue);
                }

                if (t == typeof(ushort))
                {
                    return (ushort)(Rand.Next(ushort.MaxValue - ushort.MinValue + 1) + ushort.MinValue);
                }

                if (t == typeof(int))
                {
                    var bytes = new byte[4];
                    Rand.NextBytes(bytes);

                    return BitConverter.ToInt32(bytes, 0);
                }

                if (t == typeof(uint))
                {
                    var bytes = new byte[4];
                    Rand.NextBytes(bytes);

                    return BitConverter.ToUInt32(bytes, 0);
                }

                if (t == typeof(long))
                {
                    var bytes = new byte[8];
                    Rand.NextBytes(bytes);

                    return BitConverter.ToInt64(bytes, 0);
                }

                if (t == typeof(ulong))
                {
                    var bytes = new byte[8];
                    Rand.NextBytes(bytes);

                    return BitConverter.ToUInt64(bytes, 0);
                }

                if (t == typeof(float))
                {
                    var bytes = new byte[4];
                    Rand.NextBytes(bytes);

                    var f = BitConverter.ToSingle(bytes, 0);
                    if (float.IsNaN(f))
                        f = (float)RandomValue<short>();
                    return f;
                }

                if (t == typeof(double))
                {
                    var bytes = new byte[8];
                    Rand.NextBytes(bytes);

                    var d = BitConverter.ToDouble(bytes, 0);
                    if (double.IsNaN(d))
                        d = (double)RandomValue<short>();
                    return d;
                }

                if (t == typeof(char))
                {
                    var roll = Rand.Next(ASCII.Length);

                    return ASCII[roll];
                }

                if (t == typeof(bool))
                {
                    return (Rand.Next(2) == 1);
                }

                throw new InvalidOperationException();
            }

            if (t == typeof(decimal))
            {
                return new decimal((int)typeof(int).RandomValue(), (int)typeof(int).RandomValue(), (int)typeof(int).RandomValue(), false, 28);
            }

            if (t == typeof(string))
            {
                int start = stringValueAllowEmpty ? 0 : 1;
                var len = Rand.Next(start, 28);
                var c = new char[len];
                for (var i = 0; i < c.Length; i++)
                {
                    c[i] = (char)typeof(char).RandomValue();
                }

                return new string(c);
            }

            if (t == typeof(DateTime))
            {
                var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);

                var bytes = new byte[4];
                Rand.NextBytes(bytes);

                var secsOffset = BitConverter.ToInt32(bytes, 0);

                var retDate = epoch.AddSeconds(secsOffset);

                return retDate;
            }

            if (t == typeof(TimeSpan))
            {
                return new TimeSpan(RandomValue<DateTime>().Ticks);
            }

            if (t == typeof(DataTable))
            {
                DataTable dt = new DataTable();
                int coluCount = Rand.Next(10, 30);
                for (int i = 0; i < coluCount; i++)
                {
                    dt.Columns.Add(RandomHelper.RandomValue<string>(false), typeof(object));
                }
                int rowCount = Rand.Next(20, 50);
                for (int i = 0; i < rowCount; i++)
                {
                    var row = new object[coluCount];
                    for (int zi = 0; zi < coluCount; zi++)
                    {
                        row[zi] = RandomHelper.RandomValue<object>();
                    }
                    dt.Rows.Add(row);
                }
                return dt;
            }

            if (t.IsNullable())
            {
                // leave it unset
                if (Rand.Next(2) == 0)
                {
                    // null!
                    return Activator.CreateInstance(t);
                }

                var underlying = Nullable.GetUnderlyingType(t);
                var val = underlying.RandomValue(stringValueAllowEmpty);

                var cons = t.GetConstructor(new[] { underlying });

                return cons.Invoke(new object[] { val });
            }

            if (t.IsEnum)
            {
                var allValues = Enum.GetValues(t);
                var ix = Rand.Next(allValues.Length);

                return allValues.GetValue(ix);
            }

            if (t.IsArray)
            {
                var valType = t.GetElementType();
                var len = Rand.Next(20, 50);
                var ret = Array.CreateInstance(valType, len);
                //var add = t.GetMethod("SetValue");
                for (var i = 0; i < len; i++)
                {
                    var elem = valType.RandomValue(stringValueAllowEmpty);
                    ret.SetValue(elem, i);
                }

                return ret;
            }

            if (t.IsGenericType)
            {
                var defind = t.GetGenericTypeDefinition();
                if (defind == typeof(HashSet<>))
                {
                    var valType = t.GetGenericArguments()[0];
                    var ret = Activator.CreateInstance(t);
                    var add = t.GetMethod("Add");
                    var contains = t.GetMethod("Contains");

                    var len = Rand.Next(20, 50);
                    for (var i = 0; i < len; i++)
                    {
                        var elem = valType.RandomValue(stringValueAllowEmpty);
                        while (elem == null || (bool)contains.Invoke(ret, new object[] { elem }))
                            elem = valType.RandomValue(stringValueAllowEmpty);
                        add.Invoke(ret, new object[] { elem });
                    }

                    return ret;
                }
                if (defind == typeof(Dictionary<,>))
                {
                    var keyType = t.GetGenericArguments()[0];
                    var valType = t.GetGenericArguments()[1];
                    var ret = Activator.CreateInstance(t);
                    var add = t.GetMethod("Add");
                    var contains = t.GetMethod("ContainsKey");

                    var len = Rand.Next(20, 50);
                    if (keyType == typeof(Boolean))
                        len = 2;
                    for (var i = 0; i < len; i++)
                    {
                        var val = valType.RandomValue(stringValueAllowEmpty);
                        var key = keyType.RandomValue(stringValueAllowEmpty);
                        while (key == null || (bool)contains.Invoke(ret, new object[] { key }))
                            key = keyType.RandomValue(stringValueAllowEmpty);
                        add.Invoke(ret, new object[] { key, val });
                    }

                    return ret;
                }
                if (defind == typeof(List<>))
                {
                    var valType = t.GetGenericArguments()[0];
                    var ret = Activator.CreateInstance(t);
                    var add = t.GetMethod("Add");

                    var len = Rand.Next(20, 50);
                    for (var i = 0; i < len; i++)
                    {
                        var elem = valType.RandomValue(stringValueAllowEmpty);
                        add.Invoke(ret, new object[] { elem });
                    }

                    return ret;
                }
                if (defind == typeof(ArraySegment<>))
                {
                    var valType = t.GetGenericArguments()[0];
                    var ary = valType.MakeArrayType().RandomValue(stringValueAllowEmpty);
                    var lenT = ary.GetType().GetProperty("Length");
                    var offset = Rand.Next(0, (int)lenT.GetValue(ary) - 1);
                    var len = (int)lenT.GetValue(ary) - offset;

                    return Activator.CreateInstance(t, ary, offset, len);
                }
            }

            if (t == typeof(Guid))
                return Guid.NewGuid();

            if (t == typeof(object))
            {
                var code = Rand.Next(0, 9);
                switch (code)
                {
                    case 0:
                        return RandomValue<int>();
                    case 1:
                        return RandomValue<long>();
                    case 2:
                        return RandomValue<Char>();
                    case 3:
                        return RandomValue<DateTime>();
                    case 4:
                        return RandomValue<string>(stringValueAllowEmpty);
                    case 5:
                        return RandomValue<Guid>();
                    case 6:
                        return RandomValue<decimal>();
                    case 7:
                        return RandomValue<double>();
                    case 8:
                        return RandomValue<float>();
                    default:
                        return RandomValue<short>();
                }
            }

            //model
            var retObj = Activator.CreateInstance(t);
            foreach (var p in t.GetFields())
            {
                //if (Rand.Next(5) == 0) continue;

                var fieldType = p.FieldType;

                p.SetValue(retObj, fieldType.RandomValue(stringValueAllowEmpty));
            }

            foreach (var p in t.GetProperties())
            {
                //if (Rand.Next(5) == 0) continue;
                if (p.CanWrite && p.CanRead)
                {
                    var fieldType = p.PropertyType;

                    p.SetValue(retObj, fieldType.RandomValue(stringValueAllowEmpty));
                }
            }

            return retObj;
        }

19 View Source File : RandomHelper.cs
License : MIT License
Project Creator : 1996v

public static object RandomValue(this Type t, bool stringValueAllowEmpty = true)
        {
            if (t.IsPrimitive)
            {
                if (t == typeof(byte))
                {
                    return (byte)(Rand.Next(byte.MaxValue - byte.MinValue + 1) + byte.MinValue);
                }

                if (t == typeof(sbyte))
                {
                    return (sbyte)(Rand.Next(sbyte.MaxValue - sbyte.MinValue + 1) + sbyte.MinValue);
                }

                if (t == typeof(short))
                {
                    return (short)(Rand.Next(short.MaxValue - short.MinValue + 1) + short.MinValue);
                }

                if (t == typeof(ushort))
                {
                    return (ushort)(Rand.Next(ushort.MaxValue - ushort.MinValue + 1) + ushort.MinValue);
                }

                if (t == typeof(int))
                {
                    var bytes = new byte[4];
                    Rand.NextBytes(bytes);

                    return BitConverter.ToInt32(bytes, 0);
                }

                if (t == typeof(uint))
                {
                    var bytes = new byte[4];
                    Rand.NextBytes(bytes);

                    return BitConverter.ToUInt32(bytes, 0);
                }

                if (t == typeof(long))
                {
                    var bytes = new byte[8];
                    Rand.NextBytes(bytes);

                    return BitConverter.ToInt64(bytes, 0);
                }

                if (t == typeof(ulong))
                {
                    var bytes = new byte[8];
                    Rand.NextBytes(bytes);

                    return BitConverter.ToUInt64(bytes, 0);
                }

                if (t == typeof(float))
                {
                    var bytes = new byte[4];
                    Rand.NextBytes(bytes);

                    var f = BitConverter.ToSingle(bytes, 0);
                    if (float.IsNaN(f))
                        f = (float)RandomValue<short>();
                    return f;
                }

                if (t == typeof(double))
                {
                    var bytes = new byte[8];
                    Rand.NextBytes(bytes);

                    var d= BitConverter.ToDouble(bytes, 0);
                    if (double.IsNaN(d))
                        d = (double)RandomValue<short>();
                    return d;
                }

                if (t == typeof(char))
                {
                    var roll = Rand.Next(ASCII.Length);

                    return ASCII[roll];
                }

                if (t == typeof(bool))
                {
                    return (Rand.Next(2) == 1);
                }

                throw new InvalidOperationException();
            }

            if (t == typeof(decimal))
            {
                return new decimal((int)typeof(int).RandomValue(), (int)typeof(int).RandomValue(), (int)typeof(int).RandomValue(), false, 28);
            }

            if (t == typeof(string))
            {
                int start = stringValueAllowEmpty ? 0 : 1;
                var len = Rand.Next(start, 40);
                var c = new char[len];
                for (var i = 0; i < c.Length; i++)
                {
                    c[i] = (char)typeof(char).RandomValue();
                }

                return new string(c);
            }

            if (t == typeof(DateTime))
            {
                var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);

                var bytes = new byte[4];
                Rand.NextBytes(bytes);

                var secsOffset = BitConverter.ToInt32(bytes, 0);

                var retDate = epoch.AddSeconds(secsOffset);

                return retDate;
            }

            if (t == typeof(TimeSpan))
            {
                return new TimeSpan(RandomValue<DateTime>().Ticks);
            }

            if (t == typeof(DataTable))
            {
                DataTable dt = new DataTable();
                int coluCount = Rand.Next(10, 30);
                for (int i = 0; i < coluCount; i++)
                {
                    string n = RandomHelper.RandomValue<string>(false);
                    while(dt.Columns.Contains(n))
                        n = RandomHelper.RandomValue<string>(false);
                    dt.Columns.Add(n, typeof(object));
                }
                int rowCount = Rand.Next(20, 50);
                for (int i = 0; i < rowCount; i++)
                {
                    var row = new object[coluCount];
                    for (int zi = 0; zi < coluCount; zi++)
                    {
                        row[zi] = RandomHelper.RandomValue<object>();
                    }
                    dt.Rows.Add(row);
                }
                return dt;
            }

            if (t.IsNullable())
            {
                // leave it unset
                if (Rand.Next(2) == 0)
                {
                    // null!
                    return Activator.CreateInstance(t);
                }

                var underlying = Nullable.GetUnderlyingType(t);
                var val = underlying.RandomValue(stringValueAllowEmpty);

                var cons = t.GetConstructor(new[] { underlying });

                return cons.Invoke(new object[] { val });
            }

            if (t.IsEnum)
            {
                var allValues = Enum.GetValues(t);
                var ix = Rand.Next(allValues.Length);

                return allValues.GetValue(ix);
            }

            if (t.IsArray)
            {
                var valType = t.GetElementType();
                var len = Rand.Next(20, 50);
                var ret = Array.CreateInstance(valType, len);
                //var add = t.GetMethod("SetValue");
                for (var i = 0; i < len; i++)
                {
                    var elem = valType.RandomValue(stringValueAllowEmpty);
                    ret.SetValue(elem, i);
                }

                return ret;
            }

            if (t.IsGenericType)
            {
                var defind = t.GetGenericTypeDefinition();
                if (defind == typeof(HashSet<>))
                {
                    var valType = t.GetGenericArguments()[0];
                    var ret = Activator.CreateInstance(t);
                    var add = t.GetMethod("Add");
                    var contains = t.GetMethod("Contains");

                    var len = Rand.Next(20, 50);
                    for (var i = 0; i < len; i++)
                    {
                        var elem = valType.RandomValue(stringValueAllowEmpty);
                        while (elem == null || (bool)contains.Invoke(ret, new object[] { elem }))
                            elem = valType.RandomValue(stringValueAllowEmpty);
                        add.Invoke(ret, new object[] { elem });
                    }

                    return ret;
                }
                if (defind == typeof(Dictionary<,>))
                {
                    var keyType = t.GetGenericArguments()[0];
                    var valType = t.GetGenericArguments()[1];
                    var ret = Activator.CreateInstance(t);
                    var add = t.GetMethod("Add");
                    var contains = t.GetMethod("ContainsKey");

                    var len = Rand.Next(20, 50);
                    if (keyType == typeof(Boolean))
                        len = 2;
                    for (var i = 0; i < len; i++)
                    {
                        var val = valType.RandomValue(stringValueAllowEmpty);
                        var key = keyType.RandomValue(stringValueAllowEmpty);
                       

                        while (key == null || (bool)contains.Invoke(ret, new object[] { key }))
                            key = keyType.RandomValue(stringValueAllowEmpty);
                        add.Invoke(ret, new object[] { key, val });
                    }

                    return ret;
                }
                if (defind == typeof(List<>))
                {
                    var valType = t.GetGenericArguments()[0];
                    var ret = Activator.CreateInstance(t);
                    var add = t.GetMethod("Add");

                    var len = Rand.Next(20, 50);
                    for (var i = 0; i < len; i++)
                    {
                        var elem = valType.RandomValue(stringValueAllowEmpty);
                        add.Invoke(ret, new object[] { elem });
                    }

                    return ret;
                }
                if (defind == typeof(ArraySegment<>))
                {
                    var valType = t.GetGenericArguments()[0];
                    var ary = valType.MakeArrayType().RandomValue(stringValueAllowEmpty);
                    var lenT = ary.GetType().GetProperty("Length");
                    var offset = Rand.Next(0, (int)lenT.GetValue(ary) - 1);
                    var len = (int)lenT.GetValue(ary) - offset;

                    return Activator.CreateInstance(t, ary, offset, len);
                }
            }

            if (t == typeof(Guid))
                return Guid.NewGuid();

            if (t == typeof(object))
            {
                var code = Rand.Next(0, 9);
                switch (code)
                {
                    case 0:
                        return RandomValue<int>();
                    case 1:
                        return RandomValue<long>();
                    case 2:
                        return RandomValue<Char>();
                    case 3:
                        return RandomValue<DateTime>();
                    case 4:
                        return RandomValue<string>(stringValueAllowEmpty);
                    case 5:
                        return RandomValue<Guid>();
                    case 6:
                        return RandomValue<decimal>();
                    case 7:
                        return RandomValue<double>();
                    case 8:
                        return RandomValue<float>();
                    default:
                        return RandomValue<short>();
                }
            }

            //model
            var retObj = Activator.CreateInstance(t);
            foreach (var p in t.GetFields())
            {
                //if (Rand.Next(5) == 0) continue;

                var fieldType = p.FieldType;

                p.SetValue(retObj, fieldType.RandomValue(stringValueAllowEmpty));
            }

            foreach (var p in t.GetProperties())
            {
                //if (Rand.Next(5) == 0) continue;
                if (p.CanWrite && p.CanRead)
                {
                    var fieldType = p.PropertyType;

                    p.SetValue(retObj, fieldType.RandomValue(stringValueAllowEmpty));
                }
            }

            return retObj;
        }

19 View Source File : ClientSideCaching.cs
License : MIT License
Project Creator : 2881099

public void After(InterceptorAfterEventArgs args)
                {
                    switch (args.Command._command)
                    {
                        case "GET":
                            if (_iscached == false && args.Exception == null)
                            {
                                var getkey = args.Command.GetKey(0);
                                if (_cscc._options.KeyFilter?.Invoke(getkey) != false)
                                    _cscc.SetCacheValue(args.Command._command, getkey, args.ValueType, args.Value);
                            }
                            break;
                        case "MGET":
                            if (_iscached == false && args.Exception == null)
                            {
                                if (args.Value is Array valueArr)
                                {
                                    var valueArrElementType = args.ValueType.GetElementType();
                                    var sourceArrLen = valueArr.Length;
                                    for (var a = 0; a < sourceArrLen; a++)
                                    {
                                        var getkey = args.Command.GetKey(a);
                                        if (_cscc._options.KeyFilter?.Invoke(getkey) != false)
                                            _cscc.SetCacheValue("GET", getkey, valueArrElementType, valueArr.GetValue(a));
                                    }
                                }
                            }
                            break;
                        default:
                            if (args.Command._keyIndexes.Any())
                            {
                                var cmdset = CommandSets.Get(args.Command._command);
                                if (cmdset != null &&
                                    (cmdset.Flag & CommandSets.ServerFlag.write) == CommandSets.ServerFlag.write &&
                                    (cmdset.Tag & CommandSets.ServerTag.write) == CommandSets.ServerTag.write &&
                                    (cmdset.Tag & [email protected]) == [email protected])
                                {
                                    _cscc.RemoveCache(args.Command._keyIndexes.Select((item, index) => args.Command.GetKey(index)).ToArray());
                                }
                            }
                            break;
                    }
                }

19 View Source File : InternalExtensions.cs
License : MIT License
Project Creator : 2881099

public static object FromObject(this Type targetType, object value, Encoding encoding = null)
    {
        if (targetType == typeof(object)) return value;
        if (encoding == null) encoding = Encoding.UTF8;
        var valueIsNull = value == null;
        var valueType = valueIsNull ? typeof(string) : value.GetType();
        if (valueType == targetType) return value;
        if (valueType == typeof(byte[])) //byte[] -> guid
        {
            if (targetType == typeof(Guid))
            {
                var bytes = value as byte[];
                return Guid.TryParse(BitConverter.ToString(bytes, 0, Math.Min(bytes.Length, 36)).Replace("-", ""), out var tryguid) ? tryguid : Guid.Empty;
            }
            if (targetType == typeof(Guid?))
            {
                var bytes = value as byte[];
                return Guid.TryParse(BitConverter.ToString(bytes, 0, Math.Min(bytes.Length, 36)).Replace("-", ""), out var tryguid) ? (Guid?)tryguid : null;
            }
        }
        if (targetType == typeof(byte[])) //guid -> byte[]
        {
            if (valueIsNull) return null;
            if (valueType == typeof(Guid) || valueType == typeof(Guid?))
            {
                var bytes = new byte[16];
                var guidN = ((Guid)value).ToString("N");
                for (var a = 0; a < guidN.Length; a += 2)
                    bytes[a / 2] = byte.Parse($"{guidN[a]}{guidN[a + 1]}", NumberStyles.HexNumber);
                return bytes;
            }
            return encoding.GetBytes(value.ToInvariantCultureToString());
        }
        else if (targetType.IsArray)
        {
            if (value is Array valueArr)
            {
                var targetElementType = targetType.GetElementType();
                var sourceArrLen = valueArr.Length;
                var target = Array.CreateInstance(targetElementType, sourceArrLen);
                for (var a = 0; a < sourceArrLen; a++) target.SetValue(targetElementType.FromObject(valueArr.GetValue(a), encoding), a);
                return target;
            }
            //if (value is IList valueList)
            //{
            //    var targetElementType = targetType.GetElementType();
            //    var sourceArrLen = valueList.Count;
            //    var target = Array.CreateInstance(targetElementType, sourceArrLen);
            //    for (var a = 0; a < sourceArrLen; a++) target.SetValue(targetElementType.FromObject(valueList[a], encoding), a);
            //    return target;
            //}
        }
        var func = _dicFromObject.GetOrAdd(targetType, tt =>
        {
            if (tt == typeof(object)) return vs => vs;
            if (tt == typeof(string)) return vs => vs;
            if (tt == typeof(char[])) return vs => vs == null ? null : vs.ToCharArray();
            if (tt == typeof(char)) return vs => vs == null ? default(char) : vs.ToCharArray(0, 1).FirstOrDefault();
            if (tt == typeof(bool)) return vs =>
            {
                if (vs == null) return false;
                switch (vs.ToLower())
                {
                    case "true":
                    case "1":
                        return true;
                }
                return false;
            };
            if (tt == typeof(bool?)) return vs =>
            {
                if (vs == null) return false;
                switch (vs.ToLower())
                {
                    case "true":
                    case "1":
                        return true;
                    case "false":
                    case "0":
                        return false;
                }
                return null;
            };
            if (tt == typeof(byte)) return vs => vs == null ? 0 : (byte.TryParse(vs, NumberStyles.Any, null, out var tryval) ? tryval : 0);
            if (tt == typeof(byte?)) return vs => vs == null ? null : (byte.TryParse(vs, NumberStyles.Any, null, out var tryval) ? (byte?)tryval : null);
            if (tt == typeof(decimal)) return vs => vs == null ? 0 : (decimal.TryParse(vs, NumberStyles.Any, null, out var tryval) ? tryval : 0);
            if (tt == typeof(decimal?)) return vs => vs == null ? null : (decimal.TryParse(vs, NumberStyles.Any, null, out var tryval) ? (decimal?)tryval : null);
            if (tt == typeof(double)) return vs => vs == null ? 0 : (double.TryParse(vs, NumberStyles.Any, null, out var tryval) ? tryval : 0);
            if (tt == typeof(double?)) return vs => vs == null ? null : (double.TryParse(vs, NumberStyles.Any, null, out var tryval) ? (double?)tryval : null);
            if (tt == typeof(float)) return vs => vs == null ? 0 : (float.TryParse(vs, NumberStyles.Any, null, out var tryval) ? tryval : 0);
            if (tt == typeof(float?)) return vs => vs == null ? null : (float.TryParse(vs, NumberStyles.Any, null, out var tryval) ? (float?)tryval : null);
            if (tt == typeof(int)) return vs => vs == null ? 0 : (int.TryParse(vs, NumberStyles.Any, null, out var tryval) ? tryval : 0);
            if (tt == typeof(int?)) return vs => vs == null ? null : (int.TryParse(vs, NumberStyles.Any, null, out var tryval) ? (int?)tryval : null);
            if (tt == typeof(long)) return vs => vs == null ? 0 : (long.TryParse(vs, NumberStyles.Any, null, out var tryval) ? tryval : 0);
            if (tt == typeof(long?)) return vs => vs == null ? null : (long.TryParse(vs, NumberStyles.Any, null, out var tryval) ? (long?)tryval : null);
            if (tt == typeof(sbyte)) return vs => vs == null ? 0 : (sbyte.TryParse(vs, NumberStyles.Any, null, out var tryval) ? tryval : 0);
            if (tt == typeof(sbyte?)) return vs => vs == null ? null : (sbyte.TryParse(vs, NumberStyles.Any, null, out var tryval) ? (sbyte?)tryval : null);
            if (tt == typeof(short)) return vs => vs == null ? 0 : (short.TryParse(vs, NumberStyles.Any, null, out var tryval) ? tryval : 0);
            if (tt == typeof(short?)) return vs => vs == null ? null : (short.TryParse(vs, NumberStyles.Any, null, out var tryval) ? (short?)tryval : null);
            if (tt == typeof(uint)) return vs => vs == null ? 0 : (uint.TryParse(vs, NumberStyles.Any, null, out var tryval) ? tryval : 0);
            if (tt == typeof(uint?)) return vs => vs == null ? null : (uint.TryParse(vs, NumberStyles.Any, null, out var tryval) ? (uint?)tryval : null);
            if (tt == typeof(ulong)) return vs => vs == null ? 0 : (ulong.TryParse(vs, NumberStyles.Any, null, out var tryval) ? tryval : 0);
            if (tt == typeof(ulong?)) return vs => vs == null ? null : (ulong.TryParse(vs, NumberStyles.Any, null, out var tryval) ? (ulong?)tryval : null);
            if (tt == typeof(ushort)) return vs => vs == null ? 0 : (ushort.TryParse(vs, NumberStyles.Any, null, out var tryval) ? tryval : 0);
            if (tt == typeof(ushort?)) return vs => vs == null ? null : (ushort.TryParse(vs, NumberStyles.Any, null, out var tryval) ? (ushort?)tryval : null);
            if (tt == typeof(DateTime)) return vs => vs == null ? DateTime.MinValue : (DateTime.TryParse(vs, out var tryval) ? tryval : DateTime.MinValue);
            if (tt == typeof(DateTime?)) return vs => vs == null ? null : (DateTime.TryParse(vs, out var tryval) ? (DateTime?)tryval : null);
            if (tt == typeof(DateTimeOffset)) return vs => vs == null ? DateTimeOffset.MinValue : (DateTimeOffset.TryParse(vs, out var tryval) ? tryval : DateTimeOffset.MinValue);
            if (tt == typeof(DateTimeOffset?)) return vs => vs == null ? null : (DateTimeOffset.TryParse(vs, out var tryval) ? (DateTimeOffset?)tryval : null);
            if (tt == typeof(TimeSpan)) return vs => vs == null ? TimeSpan.Zero : (TimeSpan.TryParse(vs, out var tryval) ? tryval : TimeSpan.Zero);
            if (tt == typeof(TimeSpan?)) return vs => vs == null ? null : (TimeSpan.TryParse(vs, out var tryval) ? (TimeSpan?)tryval : null);
            if (tt == typeof(Guid)) return vs => vs == null ? Guid.Empty : (Guid.TryParse(vs, out var tryval) ? tryval : Guid.Empty);
            if (tt == typeof(Guid?)) return vs => vs == null ? null : (Guid.TryParse(vs, out var tryval) ? (Guid?)tryval : null);
            if (tt == typeof(BigInteger)) return vs => vs == null ? 0 : (BigInteger.TryParse(vs, NumberStyles.Any, null, out var tryval) ? tryval : 0);
            if (tt == typeof(BigInteger?)) return vs => vs == null ? null : (BigInteger.TryParse(vs, NumberStyles.Any, null, out var tryval) ? (BigInteger?)tryval : null);
            if (tt.NullableTypeOrThis().IsEnum)
            {
                var tttype = tt.NullableTypeOrThis();
                var ttdefval = tt.CreateInstanceGetDefaultValue();
                return vs =>
                {
                    if (string.IsNullOrWhiteSpace(vs)) return ttdefval;
                    return Enum.Parse(tttype, vs, true);
                };
            }
            var localTargetType = targetType;
            var localValueType = valueType;
            return vs =>
            {
                if (vs == null) return null;
                throw new NotSupportedException($"convert failed {localValueType.DisplayCsharp()} -> {localTargetType.DisplayCsharp()}");
            };
        });
        var valueStr = valueIsNull ? null : (valueType == typeof(byte[]) ? encoding.GetString(value as byte[]) : value.ToInvariantCultureToString());
        return func(valueStr);
    }

19 View Source File : MicroVM.Assembler.cs
License : MIT License
Project Creator : a-downing

static bool TryStringToOpcode(string str, out CPU.Opcode opcode) {
            var names = Enum.GetNames(typeof(CPU.Opcode));
            var values = Enum.GetValues(typeof(CPU.Opcode));
            str = str.ToUpperInvariant();
            
            for(int i = 0; i < names.Length; i++) {
                if(names[i] == str) {
                    opcode = (CPU.Opcode)values.GetValue(i);
                    return true;
                }
            }

            opcode = 0;
            return false;
        }

19 View Source File : MicroVM.Assembler.cs
License : MIT License
Project Creator : a-downing

static bool TryStringToCond(string str, out CPU.Cond cond) {
            var names = Enum.GetNames(typeof(CPU.Cond));
            var values = Enum.GetValues(typeof(CPU.Cond));
            str = str.ToUpperInvariant();
            
            for(int i = 0; i < names.Length; i++) {
                if(names[i] == str) {
                    cond = (CPU.Cond)values.GetValue(i);
                    return true;
                }
            }

            cond = 0;
            return false;
        }

19 View Source File : CommonUtils.cs
License : Apache License 2.0
Project Creator : AantCoder

static string Process(object obj, int level, string prefLine, Dictionary<object, int> forParentLink, HashSet<string> excludeTypes)
        {
            try
            {
                if (obj == null) return "";
                Type type = obj.GetType();
                if (excludeTypes.Contains(type.Name)) return "<skip>";
                if (type == typeof(DateTime))
                {
                    return ((DateTime)obj).ToString("g");
                }
                else if (type.IsValueType || type == typeof(string))
                {
                    return obj.ToString();
                }
                else if (type.IsArray || obj is IEnumerable)
                {
                    string elementType = null;
                    Array array = null;

                    if (type.IsArray)
                    {
                        var tt = Type.GetType(type.FullName.Replace("[]", string.Empty));
                        if (tt != null)
                        {
                            elementType = tt.ToString();
                            if (excludeTypes.Contains(tt.Name)) return "<skips>";
                        }
                        //else return "<EEEEEEE" + type.FullName;
                        array = obj as Array;
                    }
                    else
                    {
                        //как лучше узнать кол-во и тип?
                        int cnt = 0;
                        foreach (var o in obj as IEnumerable) cnt++;
                        array = Array.CreateInstance(typeof(object), cnt);
                        int i = 0;
                        foreach (var o in obj as IEnumerable)
                        {
                            if (elementType == null && o != null)
                            {
                                var tt = o.GetType();
                                if (excludeTypes.Contains(tt.Name)) return "<skips>";
                                elementType = tt.ToString();
                            }
                            array.SetValue(o, i++);
                        }
                    }

                    if (elementType == null) elementType = "Object";

                    if (excludeTypes.Contains(elementType)) return "<skips>";

                    var info = "<" + elementType + "[" + array.Length.ToString() + "]" + ">";

                    if (level == 0)
                    {
                        return info + "[...]";
                    }

                    if (array.Length > 0)
                    {
                        var ress = new string[array.Length];
                        var resl = 0;
                        for (int i = 0; i < array.Length; i++)
                        {
                            ress[i] = Process(array.GetValue(i), level - 1, prefLine + PrefLineTab, forParentLink, excludeTypes);
                            resl += ress[i].Length;
                        }

                        if (resl < LineLength)
                        {
                            var res = info + "[" + ress[0];
                            for (int i = 1; i < ress.Length; i++)
                            {
                                res += ", " + ress[i];
                            }
                            return res + "]";
                        }
                        else
                        {
                            var res = info + "["
                                + Environment.NewLine + prefLine + ress[0];
                            for (int i = 1; i < ress.Length; i++)
                            {
                                res += ", "
                                    + Environment.NewLine + prefLine + ress[i];
                            }
                            return res + Environment.NewLine + prefLine + "]";
                        }
                    }
                    return info + "[]";
                }
                else if (obj is Type) return "<Type>" + obj.ToString();
                else if (type.IsClreplaced)
                {
                    var info = "<" + type.Name + ">";

                    if (forParentLink.ContainsKey(obj))
                    {
                        if (forParentLink[obj] >= level)
                            return info + "{duplicate}";
                        else
                            forParentLink[obj] = level;
                    }
                    else
                        forParentLink.Add(obj, level);

                    if (level == 0)
                    {
                        return info + "{...}";
                    }

                    FieldInfo[] fields = type.GetFields(BindingFlags.Public |
                                BindingFlags.NonPublic | BindingFlags.Instance);

                    if (fields.Length > 0)
                    {
                        var ress = new string[fields.Length];
                        var resl = 0;
                        for (int i = 0; i < fields.Length; i++)
                        {
                            object fieldValue = fields[i].GetValue(obj);
                            ress[i] = fieldValue == null
                                ? fields[i].Name + ": null"
                                : fields[i].Name + ": " + Process(fieldValue, level - 1, prefLine + PrefLineTab, forParentLink, excludeTypes);
                            resl += ress[i].Length;
                        }

                        if (resl < LineLength)
                        {
                            var res = info + "{" + ress[0];
                            for (int i = 1; i < ress.Length; i++)
                            {
                                res += ", " + ress[i];
                            }
                            return res + "}";
                        }
                        else
                        {
                            var res = info + "{"
                                + Environment.NewLine + prefLine + ress[0];
                            for (int i = 1; i < ress.Length; i++)
                            {
                                res += ", "
                                    + Environment.NewLine + prefLine + ress[i];
                            }
                            return res + Environment.NewLine + prefLine + "}";
                        }
                    }
                    return info + "{}";
                }
                else
                    throw new ArgumentException("Unknown type");
            }
            catch
            {
                return "<exception>";
            }
        }

19 View Source File : Generator.cs
License : Apache License 2.0
Project Creator : acblog

public static Post GetPost()
        {
            var types = Enum.GetValues(typeof(PostType));
            return new Post
            {
                Id = GetString(),
                Author = GetString(),
                Content = GetDoreplacedent(),
                replacedle = GetString(),
                Category = GetCategory(),
                Keywords = GetKeyword(),
                CreationTime = GetDateTimeOffset(),
                ModificationTime = GetDateTimeOffset(),
                Type = (PostType)types.GetValue(Random.Next(types.Length)),
            };
        }

19 View Source File : Deserializer.cs
License : MIT License
Project Creator : ADeltaX

public static string PrettyPrintArray(Array array, string quotes = "")
        {
            StringBuilder stringBuilder = new StringBuilder();

            for (int i = 0; i < array.Length; i++)
            {
                stringBuilder.Append("[ " + quotes + array.GetValue(i).ToString() + quotes + " ]");
                if (i < array.Length - 1)
                    stringBuilder.Append(", ");
            }

            return stringBuilder.ToString();
        }

19 View Source File : EnumControl.cs
License : MIT License
Project Creator : ahydrax

public override void Execute()
        {
            var enumType = Parameter.ParameterType;
            var enumValues = Enum.GetValues(enumType);

            var missionParam = Parameter.GetCustomAttribute<MissionParamAttribute>();
            var defaultValue = missionParam?.DefaultValue ?? enumValues.GetValue(0);

            WriteLiteral("<div clreplaced=\"input-group\">");
            WriteLiteral($"<div clreplaced=\"input-group-addon\">{Parameter.Name}</div>");
            WriteLiteral($"<select name=\"{Parameter.Name}\" clreplaced=\"form-control\">");
            foreach (var enumValue in enumValues)
            {
                var enumValueName = Enum.GetName(enumType, enumValue);
                var description = GetDescription(enumType, enumValueName);
                var value = enumValue.ToString();
                var selected = defaultValue.Equals(enumValue) ? "selected" : string.Empty;
                var label = enumValueName;
                if (description != null)
                {
                    label += $" ({description})";
                }

                WriteLiteral($"<option {selected} value=\"{value}\">{label}</option>");
            }
            WriteLiteral("</select>");
            WriteLiteral("</div>");
        }

19 View Source File : ParamDrawer.cs
License : MIT License
Project Creator : aillieo

public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
        {
            EnsureParamType();

            switch (paramType)
            {
                case ParamType.Unknown:
                    Debug.LogError("Unknown type");
                    break;
                case ParamType.Normal:
                    EditorGUI.PropertyField(position, property.FindPropertyRelative("value"), new GUIContent(property.FindPropertyRelative("key").stringValue));
                    break;
                case ParamType.Array:
                    if (reorderableList == null)
                    {
                        CreateReorderableList(property);
                    }
                    reorderableList.DoList(position);
                    break;
                case ParamType.Enum:
                    Type fieldType = fieldInfo.FieldType;
                    Type elementType = fieldType.GetElementType();
                    string enumTypeName = property.FindPropertyRelative("enumType").stringValue;
                    Type enumType = Type.GetType(enumTypeName);
                    var paramValue = property.FindPropertyRelative("value");
                    FieldInfo field = elementType.GetField("value", BindingFlags.Public | BindingFlags.Instance);
                    if (!Enum.IsDefined(enumType, paramValue.intValue))
                    {
                        paramValue.intValue = (int)Enum.GetValues(field.FieldType).GetValue(0);
                    }
                    paramValue.intValue = EditorGUI.Popup(position,property.FindPropertyRelative("key").stringValue, paramValue.intValue, enumType.GetEnumNames());
                    break;
            }
        }

19 View Source File : AudioKernelExtensions.cs
License : MIT License
Project Creator : aksyr

static ParameterDescriptionData CreateParameterDescription()
            {
                var pType = typeof(TParameters);
                if (!pType.IsEnum)
                    throw new ArgumentException("CreateDSPNode<Parameters, Providers, T> must have Parameters as an enum.");

                var pValues = Enum.GetValues(pType);
                for (var i = 0; i < pValues.Length; i++)
                {
                    if ((int)pValues.GetValue(i) != i)
                        throw new ArgumentException("CreateDSPNode<Parameters, Providers, T> enum values must start at 0 and be consecutive");
                }

                var paramsDescriptions = Utility.AllocateUnsafe<DSPParameterDescription>(pValues.Length, Allocator.Persistent, true);
                for (var i = 0; i < pValues.Length; i++)
                {
                    paramsDescriptions[i].Min = float.MinValue;
                    paramsDescriptions[i].Max = float.MaxValue;
                    paramsDescriptions[i].DefaultValue = 0.0f;
                    var field = pType.GetField(Enum.GetName(pType, pValues.GetValue(i)));

                    var rangeAttr = (ParameterRangeAttribute)Attribute.GetCustomAttribute(field, typeof(ParameterRangeAttribute));
                    if (rangeAttr != null)
                    {
                        paramsDescriptions[i].Min = rangeAttr.Min;
                        paramsDescriptions[i].Max = rangeAttr.Max;
                    }

                    var defValAttr = (ParameterDefaultAttribute)Attribute.GetCustomAttribute(field, typeof(ParameterDefaultAttribute));
                    if (defValAttr != null)
                    {
                        paramsDescriptions[i].DefaultValue = defValAttr.DefaultValue;
                    }
                }

                var data = new ParameterDescriptionData
                {
                    Descriptions = paramsDescriptions,
                    ParameterCount = pValues.Length
                };

                return data;
            }

19 View Source File : AudioKernelExtensions.cs
License : MIT License
Project Creator : aksyr

static SampleProviderDescriptionData CreateSampleProviderDescription()
            {
                var pType = typeof(TProviders);
                if (!pType.IsEnum)
                    throw new ArgumentException("CreateDSPNode<Parameters, Providers, T> must have Providers as an enum.");

                var pValues = Enum.GetValues(pType);
                for (var i = 0; i < pValues.Length; i++)
                {
                    if ((int)pValues.GetValue(i) != i)
                        throw new ArgumentException("CreateDSPNode<Parameters, Providers, T> enum values must start at 0 and be consecutive");
                }

                var provsDescriptions = Utility.AllocateUnsafe<DSPSampleProviderDescription>(pValues.Length, Allocator.Persistent, true);
                for (var i = 0; i < pValues.Length; i++)
                {
                    provsDescriptions[i].m_IsArray = false;
                    provsDescriptions[i].m_Size = -1;

                    var field = pType.GetField(Enum.GetName(pType, pValues.GetValue(i)));

                    var arrayAttr = (SampleProviderArrayAttribute)Attribute.GetCustomAttribute(field, typeof(SampleProviderArrayAttribute));
                    if (arrayAttr != null)
                    {
                        provsDescriptions[i].m_IsArray = true;
                        provsDescriptions[i].m_Size = arrayAttr.Size;
                    }
                }

                return new SampleProviderDescriptionData
                {
                    Descriptions = provsDescriptions,
                    SampleProviderCount = pValues.Length
                };
            }

19 View Source File : DataColumnEnumerator.cs
License : MIT License
Project Creator : aloneguid

public bool MoveNext()
      {
         if ((_position + 1) >= _data.Length)
            return false;

         if(_isRepeated)
         {
            int read = Read(_position + 1, out object current);

            _position += read;

            Current = current;
         }
         else
         {
            Current = _data.GetValue(++_position);
         }

         return true;
      }

19 View Source File : DataColumnEnumerator.cs
License : MIT License
Project Creator : aloneguid

private int Read(int position, out object cr)
      {
         //0 indicates start of a new row
         int prl = 0;
         int read = 0;
         var result = new TreeList(null);
         TreeList current = result;

         while(position < _data.Length)
         {
            int rl = _rls[position];

            if (rl == 0 && (current.HasValues || current != result))
            {
               break;
            }

            int lmv = rl - prl;

            if(lmv != 0)
            {
               current = current.Submerge(lmv);
            }

            object value = _data.GetValue(position);
            current.Add(value);
            read += 1;

            prl = rl;
            position += 1;
         }

         cr = result.FinalValue(_field.ClrNullableIfHasNullsType);

         if(cr == null)
         {
            cr = Array.CreateInstance(_field.ClrNullableIfHasNullsType, 0);
         }

         return read;
      }

19 View Source File : LazyColumnEnumerator.cs
License : MIT License
Project Creator : aloneguid

public bool MoveNext()
      {
         if (_offset >= (_start + _count))
         {
            Current = null;
            return false;
         }

         if(_rl == _maxRl)
         {
            //If you've reached the maximum repereplacedion level the only thing you can do is read
            //actual data from the allocated window.
            //This gets invoked immediately for flat scalar types.
            Current = _data.GetValue(_offset++);
         }
         else
         {
            ReadWindow();
         }

         return true;
      }

19 View Source File : LazyColumnEnumerator.cs
License : MIT License
Project Creator : aloneguid

private void ReadWindow()
      {
         //get the next window where RL drops down

         int prl = -1;

         for (int i = _offset; i < _start + _count; i++)
         {
            int rl = _rls[i];

            if (prl != -1 && rl != _maxRl && rl == _rl)
            {
               int count = i - _offset;

               //detecting empty list is not really possible in parquet
               //we make an replacedumption that if RL is 0, list has one element and data element is zero it's empty
               //it's a parquet format limitation
               bool isEmpty = 
                  count == 1 &&
                  rl == 0 &&
                  (_data.GetValue(_offset) == null);

               if (isEmpty)
               {
                  count = 0;
               }

               Current = new LazyColumnEnumerator(_dc,
                  _offset,
                  count,
                  _rl + 1);
               _offset = i;
               return;
            }

            prl = rl;
         }

         int finalCount = _count - (_offset - _start);
         if(finalCount == 1 && prl == 0 && (_data.GetValue(_offset) == null))
         {
            finalCount = 0;
         }

         Current = new LazyColumnEnumerator(_dc,
            _offset,
            finalCount,
            _rl + 1);
         _offset = _start + _count; //make it big
      }

19 View Source File : OtherExtensions.cs
License : MIT License
Project Creator : aloneguid

public static bool EqualTo(this Array left, Array right)
      {
         if (left.Length != right.Length)
            return false;

         for (int i = 0; i < left.Length; i++)
         {
            object il = left.GetValue(i);
            object ir = right.GetValue(i);

            if (il == null || ir == null)
            {
               return il == null && ir == null;
            }

            if (!il.Equals(ir))
               return false;
         }

         return true;
      }

19 View Source File : CertesWrapper.cs
License : GNU General Public License v3.0
Project Creator : aloopkin

public async Task<bool> RevokeCertificate(X509Certificate2 certificate, int reason)
        {
            if (certificate == null) return false;
            try
            {
                InitCertes();

                RevocationReason rr = (RevocationReason)(Enum.GetValues(RevocationReason.Unspecified.GetType())).GetValue(reason);
                await _acme.RevokeCertificate(certificate.RawData, rr, null);

                return true;
            }
            catch (Exception exp)
            {
                logger.Error($"Failed to revoke certificate with serial {certificate.GetSerialNumberString()} from CA: {ProcessCertesException(exp)}");
                return false;
            }
        }

19 View Source File : Building.cs
License : GNU General Public License v3.0
Project Creator : anderson-joyle

static VSProjectNode GetActiveProjectNode(DTE dte)
        {
            Array array = dte.ActiveSolutionProjects as Array;
            if (array != null && array.Length > 0)
            {
                Project project = array.GetValue(0) as Project;
                if (project != null)
                {
                    return project.Object as VSProjectNode;
                }
            }
            return null;
        }

19 View Source File : LocalUtils.cs
License : GNU General Public License v3.0
Project Creator : anderson-joyle

internal static VSProjectNode GetActiveProject()
        {
            Array projects = LocalUtils.DTE.ActiveSolutionProjects as Array;

            if (projects?.Length > 0)
            {
                Project project = projects.GetValue(0) as Project;
                return project?.Object as VSProjectNode;
            }
            return null;
        }

19 View Source File : NgItemWizard.cs
License : MIT License
Project Creator : andfomin

public void RunStarted(object automationObject, Dictionary<string, string> replacementsDictionary,
        WizardRunKind runKind, object[] customParams)
        {
            replacementsDictionary.TryGetValue("$solutiondirectory$", out string solutionDirectory);

            var settings = new NgItemWizardViewModel.NgItemWizardSettings();

            // Test if @angular/cli is installed globally.
            this.isNgFound = NgWizardHelper.IsNgFound(solutionDirectory);
            settings.IsNgFound = this.isNgFound;

            var dte = (DTE)automationObject;
            var activeProjects = (Array)dte.ActiveSolutionProjects;
            if (activeProjects.Length > 0)
            {
                var project = (Project)activeProjects.GetValue(0);

                // The NuGet package needs netstandard2.0. We don't support ASP.NET Core 1.x projects.
                settings.IsAspNetCore2 = NgWizardHelper.IsAspNetCore2(project);
                // Look for an existing .angular-cli.json indicating there has been already an Angular CLI app created.
                settings.IsAngularCliJsonFound = NgWizardHelper.FindFileInRootDir(project, NgWizardHelper.AngularCliJsonFileName);
                // Test if a package.json exists.
                settings.IsOldPackageJsonFound = NgWizardHelper.FindFileInRootDir(project, NgWizardHelper.PackageJsonFileName, out string packageJsonFilePath);
                // Test if an entry for "@angular/core" exists in package.json.
                settings.IsNpmAngularFound = NgWizardHelper.IsNpmAngularFound(packageJsonFilePath);

                // Automatic installation is disabled if .gitignore or package.json or tsconfig.json or Startup.cs is opened in an editor window.
                settings.IsGitignoreOpened = NgWizardHelper.IsFileOpened(project, NgWizardHelper.GitignoreFileName);
                settings.IsPackageJsonOpened = NgWizardHelper.IsFileOpened(project, NgWizardHelper.PackageJsonFileName);
                settings.IsStartupCsOpened = NgWizardHelper.IsFileOpened(project, NgWizardHelper.StartupCsFileName);
                settings.IsTsconfigJsonOpened = NgWizardHelper.IsFileOpened(project, NgWizardHelper.TsconfigJsonFileName);
            }

            // Display the wizard to the user.
            var viewModel = new NgItemWizardViewModel(settings);
            var mainWindow = new NgItemWizardWindow(viewModel);
            var accepted = mainWindow.ShowDialog().GetValueOrDefault();

            this.installAutomatically = viewModel.InstallAutomatically;

            if (!accepted)
            {
                throw new WizardCancelledException("The wizard has been cancelled by the user.");
            }
        }

19 View Source File : ObjectGenerator.cs
License : GNU General Public License v3.0
Project Creator : andysal

private static object GenerateEnum(Type enumType)
        {
            Array possibleValues = Enum.GetValues(enumType);
            if (possibleValues.Length > 0)
            {
                return possibleValues.GetValue(0);
            }
            return null;
        }

19 View Source File : LegendConverters.cs
License : MIT License
Project Creator : AngeloCresta

public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context)
		{
			ArrayList values = new ArrayList();
            values.Add(Constants.NotSetValue);

			ChartAreaCollection	areaCollection = null;
			string	areaName = "";
			if (context != null && context.Instance != null)
			{
				if (context.Instance is Legend)
				{
					Legend legend = (Legend)context.Instance;
					if(legend.Common != null && legend.Common.ChartPicture != null)
					{
						areaCollection = legend.Common.ChartPicture.ChartAreas;
					}
				}
				else if (context.Instance is ChartArea)
				{
					ChartArea area = (ChartArea)context.Instance;
					if(area.Common != null && area.Common.ChartPicture != null)
					{
						areaCollection = area.Common.ChartPicture.ChartAreas;
						areaName = area.Name;
					}
				}
				else if (context.Instance is replacedle)
				{
					replacedle replacedle = (replacedle)context.Instance;
					if(replacedle.Chart != null && replacedle.Chart.chartPicture != null)
					{
						areaCollection = replacedle.Chart.chartPicture.ChartAreas;
					}
				}

				else if (context.Instance is Annotation)
				{
					Annotation annotation = (Annotation)context.Instance;
					if(annotation.Chart != null && annotation.Chart.chartPicture != null)
					{
						areaCollection = annotation.Chart.chartPicture.ChartAreas;
					}
				}
                else if (context.Instance is IServiceProvider)
                {
                    IServiceProvider provider = context.Instance as IServiceProvider;

                    Chart chart = provider.GetService(typeof(Chart)) as Chart;

                    if (chart != null)
                    {
                        areaCollection = chart.ChartAreas;
                    }
                }
                else if (context.Instance is Array)
                {
                    if (((Array)context.Instance).Length > 0 && ((Array)context.Instance).GetValue(0) is Legend)
                    {
                        Legend legend = (Legend)((Array)context.Instance).GetValue(0);
                        if (legend.Common != null && legend.Common.ChartPicture != null)
                        {
                            areaCollection = legend.Common.ChartPicture.ChartAreas;
                        }
                    }
                    else if (((Array)context.Instance).Length > 0 && ((Array)context.Instance).GetValue(0) is ChartArea)
                    {
                        ChartArea area = (ChartArea)((Array)context.Instance).GetValue(0);
                        if (area.Common != null && area.Common.ChartPicture != null)
                        {
                            areaCollection = area.Common.ChartPicture.ChartAreas;
                        }
                    }
                    else if (((Array)context.Instance).Length > 0 && ((Array)context.Instance).GetValue(0) is replacedle)
                    {
                        replacedle replacedle = (replacedle)((Array)context.Instance).GetValue(0);
                        if (replacedle.Chart != null && replacedle.Chart.chartPicture != null)
                        {
                            areaCollection = replacedle.Chart.chartPicture.ChartAreas;
                        }
                    }

                    else if (((Array)context.Instance).Length > 0 && ((Array)context.Instance).GetValue(0) is Annotation)
                    {
                        Annotation annotation = (Annotation)((Array)context.Instance).GetValue(0);
                        if (annotation.Chart != null && annotation.Chart.chartPicture != null)
                        {
                            areaCollection = annotation.Chart.chartPicture.ChartAreas;
                        }
                    }


                }
			}

			if (areaCollection != null)
			{
				foreach(ChartArea area in areaCollection)
				{
					if(area.Name != areaName)
					{
						values.Add(area.Name);
					}
				}
			}

			return new StandardValuesCollection(values);
		}

19 View Source File : DataManagerEditors.cs
License : MIT License
Project Creator : AngeloCresta

public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context) 
		{
			if (context != null && context.Instance != null) 
			{
				// Check how many Y values in the series.
				int	yValuesNumber = 1;
				if(context.Instance is Series)
				{
					yValuesNumber = ((Series)context.Instance).YValuesPerPoint;
				}
				else if(context.Instance is Array)
				{
					Array	array = (Array)context.Instance;
					if(array.Length > 0 && array.GetValue(0) is Series)
					{
						yValuesNumber = Math.Max(yValuesNumber, ((Series)array.GetValue(0)).YValuesPerPoint);
					}
				}

				return (yValuesNumber == 1) ? UITypeEditorEditStyle.None : UITypeEditorEditStyle.DropDown;
			}
			return base.GetEditStyle(context);
		}

19 View Source File : PrinterFriendlyCharts.cs
License : MIT License
Project Creator : AngeloCresta

private Chart CreatePrinterFriendlyChart(Chart originalChart)
		{
			// Save original chart data points values and some additional properties into the stream
			MemoryStream memoryStream = new MemoryStream();
			originalChart.Serializer.Content = SerializationContents.Data;
			originalChart.Serializer.SerializableContent += ",*.ChartType,*.replacedle,*.replacedleFont,Chart.Legend,*.Enabled,Chart.ChartAreas,ChartArea.Name";
			originalChart.Serializer.Save(memoryStream);

			// Create new chart control and load data from stream
			Chart	printerChart = new System.Windows.Forms.DataVisualization.Charting.Chart();
			memoryStream.Seek(0, SeekOrigin.Begin);
			printerChart.Serializer.Load(memoryStream);
			memoryStream.Close();

			// Loop through all series
			Array	hatchingValues = Enum.GetValues(typeof(ChartHatchStyle));
			int		hatchingIndex = 1;
			foreach(Series series in printerChart.Series)
			{
				// Loop through all data points
				foreach(DataPoint point in series.Points)
				{
					// Set point colors and hatching
					point.BorderColor = Color.Black;
					point.Color = Color.White;
					point.BackSecondaryColor = Color.Black;
					point.BackHatchStyle = (ChartHatchStyle)hatchingValues.GetValue(hatchingIndex++);
					if(hatchingIndex >= hatchingValues.Length)
					{
						hatchingIndex = 1;
					}
				}
			}

			return printerChart;
		}

19 View Source File : CustomAttributesConverters.cs
License : MIT License
Project Creator : AngeloCresta

private bool IsDataPoint(object obj)
		{
            Series series = obj as Series;
			if(series != null)
			{
				return false;
			}

            Array array = obj as Array;
			if(array != null && array.Length > 0)
			{
                if (array.GetValue(0) is Series)
				{
					return false;
				}
			}
			return true;
		}

19 View Source File : CustomAttributesConverters.cs
License : MIT License
Project Creator : AngeloCresta

[SuppressMessage("Microsoft.Performance", "CA1800:DoNotCastUnnecessarily",
            Justification = "Too large of a code change to justify making this change")]
		private Series[] GetSelectedSeries(object obj)
		{
			// Get array of series
			Series[] seriesArray = new Series[0];
			if(obj is Array && ((Array)obj).Length > 0)
			{
				if(((Array)obj).GetValue(0) is Series)
				{
					seriesArray = new Series[((Array)obj).Length];
					((Array)obj).CopyTo(seriesArray, 0);
				}
				else if(((Array)obj).GetValue(0) is DataPointCustomProperties)
				{
					seriesArray = new Series[] { ((DataPointCustomProperties)((Array)obj).GetValue(0)).series };
				}
			}
			else if(obj is Series)
			{
				seriesArray = new Series[] { ((Series)obj) };
			}
			else if(obj is DataPointCustomProperties)
			{
				seriesArray = new Series[] { ((DataPointCustomProperties)obj).series };
			}

			return seriesArray;
		}

19 View Source File : MarkerStyleEditor.cs
License : MIT License
Project Creator : AngeloCresta

[SuppressMessage("Microsoft.Performance", "CA1800:DoNotCastUnnecessarily",
            Justification = "Too large of a code change to justify making this change")]
		public override void PaintValue(PaintValueEventArgs e)
		{
			if(e.Value is MarkerStyle)
			{
				// Create chart graphics object
				if(_chartGraph == null)
				{
					_chartGraph = new ChartGraphics(null);
				}
				_chartGraph.Graphics = e.Graphics;

				// Get marker properties
				DataPointCustomProperties	attributes = null;
				if(e.Context != null && e.Context.Instance != null)
				{
					// Check if several object selected
					object	attrObject = e.Context.Instance;
					if(e.Context.Instance is Array)
					{
						Array	array = (Array)e.Context.Instance;
						if(array.Length > 0)
						{
							attrObject = array.GetValue(0);
						}
					}

					// Check what kind of object is selected
					if(attrObject is Series)
					{
						attributes = (DataPointCustomProperties)attrObject;
					}
					else if(attrObject is DataPoint)
					{
						attributes = (DataPointCustomProperties)attrObject;
					}
					else if(attrObject is DataPointCustomProperties)
					{
						attributes = (DataPointCustomProperties)attrObject;
					}
					else if(attrObject is LegendItem)
					{
						attributes = new DataPointCustomProperties();
						attributes.MarkerColor = ((LegendItem)attrObject).markerColor;
						attributes.MarkerBorderColor = ((LegendItem)attrObject).markerBorderColor;
						attributes.MarkerSize = ((LegendItem)attrObject).markerSize;
					}
				}

				// Draw marker sample
				if(attributes != null && (MarkerStyle)e.Value != MarkerStyle.None)
				{
					PointF	point = new PointF(e.Bounds.X + ((float)e.Bounds.Width)/2F - 0.5F, e.Bounds.Y + ((float)e.Bounds.Height)/2F - 0.5F);
					Color color = (attributes.MarkerColor == Color.Empty) ? Color.Black : attributes.MarkerColor;
					int size = attributes.MarkerSize;
					if(size > (e.Bounds.Height - 4))
					{
						size = e.Bounds.Height - 4;
					}
					_chartGraph.DrawMarkerAbs(
						point, 
						(MarkerStyle)e.Value, 
						size, 
						color, 
						attributes.MarkerBorderColor, 
						attributes.MarkerBorderWidth,
						"", 
						Color.Empty, 
						0, 
						Color.Empty, 
						RectangleF.Empty, 
						true);
				}
			}
		}

19 View Source File : BinarySerializer.cs
License : MIT License
Project Creator : ansel86castro

private void WriteArray(Stream stream, Array array)
        {
            var len = array.Length;
            for (int i = 0; i < len; i++)
            {
                Serialize(stream, array.GetValue(i));
            }            
        }

19 View Source File : EntityExtensions.cs
License : MIT License
Project Creator : ansel86castro

private static object ToDataArray(Array array, HashSet<object> visited)
        {
            var dataArray = Array.CreateInstance(array.GetType().GetElementType(), array.GetLength(0));
            for (int i = 0; i < dataArray.GetLength(0); i++)
            {
                dataArray.SetValue(ToData(array.GetValue(i), visited), i);
            }
            return dataArray;
        }

19 View Source File : DefaultRenderer.cs
License : Apache License 2.0
Project Creator : apache

private void RenderArray(RendererMap rendererMap, Array array, TextWriter writer)
		{
			if (array.Rank != 1)
			{
				writer.Write(array.ToString());
			}
			else
			{
				writer.Write(array.GetType().Name + " {");
				int len = array.Length;

				if (len > 0)
				{
					rendererMap.FindAndRender(array.GetValue(0), writer);
					for(int i=1; i<len; i++)
					{
						writer.Write(", ");
						rendererMap.FindAndRender(array.GetValue(i), writer);
					}
				}
				writer.Write("}");
			}
		}

19 View Source File : SystemStringFormat.cs
License : Apache License 2.0
Project Creator : apache

private static void RenderArray(Array array, StringBuilder buffer)
		{
			if (array == null)
			{
				buffer.Append(SystemInfo.NullText);
			}
			else
			{
				if (array.Rank != 1)
				{
					buffer.Append(array.ToString());
				}
				else
				{
					buffer.Append("{");
					int len = array.Length;

					if (len > 0)
					{
						RenderObject(array.GetValue(0), buffer);
						for (int i = 1; i < len; i++)
						{
							buffer.Append(", ");
							RenderObject(array.GetValue(i), buffer);
						}
					}
					buffer.Append("}");
				}
			}
		}

19 View Source File : AttributesMaster.cs
License : GNU Lesser General Public License v3.0
Project Creator : ApexGameTools

public static void Refresh()
        {
            var markerAttribute = typeof(EnreplacedyAttributesEnumAttribute);

#if NETFX_CORE
            var markerAttributeInf = markerAttribute.GetTypeInfo();
            var defaultAttributeInf = typeof(DefaultEnreplacedyAttributesEnum).GetTypeInfo();
            var asm = markerAttributeInf.replacedembly;

            attributesEnumType = asm.DefinedTypes.Where(t => t.IsEnum && t.CustomAttributes.Any(a => a.AttributeType == markerAttribute) && t != defaultAttributeInf).FirstOrDefault().AsType();
#else
            var asm = markerAttribute.replacedembly;
            attributesEnumType = asm.GetTypes().Where(t => t.IsEnum && Attribute.IsDefined(t, markerAttribute) && t != typeof(DefaultEnreplacedyAttributesEnum)).FirstOrDefault();
#endif
            if (attributesEnumType == null)
            {
                attributesEnabled = false;
                highestOrderBit = 0;
                attributesEnumType = typeof(DefaultEnreplacedyAttributesEnum);
            }
            else
            {
                var vals = Enum.GetValues(attributesEnumType);
                highestOrderBit = (int)Math.Log((int)vals.GetValue(vals.Length - 1), 2);
                attributesEnabled = true;
            }
        }

19 View Source File : RepairWindow.cs
License : GNU Lesser General Public License v3.0
Project Creator : ApexGameTools

private void DrawMismatchFix()
        {
            EditorGUILayout.BeginVertical("Box");
            EditorGUILayout.LabelField("Mismatch Resolution", EditorStyling.Skinned.boldreplacedle);
            EditorGUILayout.Separator();
            EditorGUILayout.LabelField("For each type in which a mismatch between a field's or property's type and the actual value was found, you will see a section below.\n\nThe left hand side of the list shows all fields and properties with mismatched values.\n\nThe right hand side is where you can provide a new value if applicable.\nYou can also leave it blank in which case the value will be reset to its default value.", SharedStyles.BuiltIn.wrappedText);
            EditorGUILayout.BeginHorizontal();
            GUILayout.FlexibleSpace();
            EditorGUIUtility.labelWidth = 100f;
            _utility.hideApexTypes = EditorGUILayout.Toggle("Hide Apex types", _utility.hideApexTypes);
            EditorGUIUtility.labelWidth = 0f;
            EditorGUILayout.EndHorizontal();
            EditorGUILayout.EndVertical();

            _scrollPos = EditorGUILayout.BeginScrollView(_scrollPos, "Box");

            var labelContent = new GUIContent();
            foreach (var mm in _mismatchResolution)
            {
                EditorGUILayout.BeginVertical("Box");
                EditorGUILayout.BeginHorizontal(SharedStyles.BuiltIn.lisreplacedemHeader);
                labelContent.text = mm.parentName;
                EditorGUILayout.LabelField(labelContent);
                EditorGUILayout.EndHorizontal();

                labelContent.tooltip = string.Empty;
                foreach (var member in mm.mismatchedMembers)
                {
                    EditorGUILayout.BeginHorizontal();
                    labelContent.text = member.item.name;
                    if (string.IsNullOrEmpty(labelContent.text))
                    {
                        labelContent.text = "Item";
                    }

                    EditorGUILayout.LabelField(labelContent);

                    labelContent.text = member.typeName;
                    EditorGUILayout.LabelField(labelContent);

                    if (member.isCorrectable)
                    {
                        EditorGUILayout.LabelField("->", GUILayout.Width(40f));

                        if (member.baseType.IsEnum)
                        {
                            var val = member.resolvedValue;
                            if (val == null)
                            {
                                var arr = Enum.GetValues(member.baseType);
                                if (arr.Length > 0)
                                {
                                    val = arr.GetValue(0);
                                }
                            }

                            if (val != null)
                            {
                                member.resolvedValue = EditorGUILayout.EnumPopup((Enum)val);
                            }
                        }
                        else
                        {
                            if (member.resolvedTypeName != null)
                            {
                                labelContent.text = member.resolvedTypeName.fullTypeName;
                            }
                            else
                            {
                                labelContent.text = "?";
                            }

                            EditorGUILayout.LabelField(labelContent);

                            if (GUILayout.Button("...", EditorStyling.Skinned.fixedButton))
                            {
                                var screenPos = EditorGUIUtility.GUIToScreenPoint(Event.current.mousePosition);
                                GenericSelectorWindow.Show<TypeNameTokens>(
                                    screenPos,
                                    "Select Type",
                                    _utility.GetAvailableTypes(member.baseType),
                                    RenderLisreplacedem,
                                    MatchItem,
                                    true,
                                    false,
                                    t =>
                                    {
                                        member.resolvedTypeName = t.Length > 0 ? t[0] : null;
                                        this.Repaint();
                                    });

                                this.Repaint();
                            }
                        }
                    }

                    EditorGUILayout.EndHorizontal();
                }

                EditorGUILayout.EndVertical();
            }

            EditorGUILayout.EndScrollView();

            EditorGUILayout.BeginHorizontal();

            if (GUILayout.Button("Back"))
            {
                if (_memberResolution.Length > 0)
                {
                    _step = Step.Members;
                }
                else if (_typeResolution.Length > 0)
                {
                    _step = Step.Types;
                }
                else
                {
                    ToStart();
                }
            }

            if (GUILayout.Button("Proceed"))
            {
                _working = true;

                EditorAsync.Execute(
                    () => _utility.GetStatus(),
                    (rs) =>
                    {
                        _status = rs;
                        _scrollPos = Vector2.zero;
                        _step = Step.Summary;

                        EndWork();
                    });
            }

            EditorGUILayout.EndHorizontal();
        }

19 View Source File : EnumController.cs
License : GNU General Public License v3.0
Project Creator : arduosoft

[HttpGet("{name}")]
        public RestMessage<Dictionary<string, string>> Get(string name)
        {
            var data = new Dictionary<string, string>();
            var result = new RestMessage<Dictionary<string, string>>(data);

            try
            {
                var values = Enum.GetValues(enumMap[name]);
                var names = Enum.GetNames(enumMap[name]);
                for (int i = 0; i < names.Length; i++)
                {
                    data[names[i]] = values.GetValue(i).ToString();
                }
            }
            catch (Exception err)
            {
                this.logger.LogError(err, "error during enum resolution");
                result.Errors.Add(new Error()
                {
                    Code = "001",
                    replacedle = "Error getting enum",
                    Description = err.Message
                });
            }
            return result;
        }

19 View Source File : EnumTogglesAttributeDrawer.cs
License : MIT License
Project Creator : arimger

protected override EnumData GetEnumData(string[] rawLabels, Array rawValues)
            {
                var labels = new List<string>();
                var values = new List<object>();
                var enumData = new EnumData
                {
                    labels = labels,
                    values = values,
                    isFlags = false
                };

                labels.AddRange(rawLabels);
                for (var i = 0; i < rawValues.Length; i++)
                {
                    values.Add(rawValues.GetValue(i));
                }

                return enumData;
            }

19 View Source File : EnumTogglesAttributeDrawer.cs
License : MIT License
Project Creator : arimger

protected override EnumData GetEnumData(string[] rawLabels, Array rawValues)
            {
                var labels = new List<string>();
                var values = new List<object>();
                var enumData = new EnumData
                {
                    isFlags = true,
                    labels = labels,
                    values = values
                };

                labels.Add("Everything");
                for (var i = 0; i < rawValues.Length; i++)
                {
                    var value = (int)rawValues.GetValue(i);
                    if (value == 0)
                    {
                        continue;
                    }

                    if (value == ~0)
                    {
                        labels[0] = rawLabels[i];
                        continue;
                    }

                    labels.Add(rawLabels[i]);
                    values.Add(value);
                    enumData.valuesSum += value;
                }

                values.Insert(0, enumData.valuesSum);
                return enumData;
            }

19 View Source File : InspectorPlusFiler.cs
License : MIT License
Project Creator : ArthurBrussee

string BuildArgs(params object[] args) {
		string ret = "";

		if (args.Length == 0)
			return "";

		foreach (object s in args) {
			if (s == null)
				continue;

			string add = s.ToString();

			if (s.GetType() == typeof(string)) {
				add = add.Replace("\"", "\\\"");
				add = "\"" + add + "\"";
			}

			if (s.GetType() == typeof(Vector3)) {
				Vector3 val = (Vector3) s;
				add = "new Vector3(" + val.x + "f," + val.y + "f," + val.z + "f)";
			}

			if (s.GetType() == typeof(InspectorPlusVar.LimitType))
				add = "InspectorPlusVar.LimitType." + add;

			if (s.GetType() == typeof(InspectorPlusVar.VectorDrawType))
				add = "InspectorPlusVar.VectorDrawType." + add;

			if (s.GetType().IsArray) {
				Array arr = s as Array;
				add = "new " + add + "{";
				for (int i = 0; i < ((Array) s).Length; i += 1) {
					add += BuildArgs(arr.GetValue(i));
					if (i + 1 < ((Array) s).Length)
						add += ",";
				}
				add += "}";
			}

			ret += "," + add;
		}

		return ret.Substring(1);
	}

19 View Source File : PreviewWindow.cs
License : GNU General Public License v2.0
Project Creator : Asixa

private void DragScene(object sender, DragEventArgs e)
        {
            Loading.Visible = true;
            Loading.Top = Loading.Left = 0;
            Loading.Width = Width;
            Loading.Height = Height;
            new Scene(((Array) e.Data.GetData(DataFormats.FileDrop)).GetValue(0).ToString());
        }

19 View Source File : MainWindow.xaml.cs
License : MIT License
Project Creator : Asixa

private void FilesDrop_Drop(object sender, DragEventArgs e)
        {
            string msg = "Drop";
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
            {
                msg = ((System.Array)e.Data.GetData(DataFormats.FileDrop)).GetValue(0).ToString();
                if (!Directory.Exists(msg)) return;
                filespath.Content = Path.GetFileNameWithoutExtension(msg);
                Fullpath.Content = msg;
                UploadPath = msg;

                BitmapImage bi = new BitmapImage();
                bi.BeginInit();
                bi.UriSource = new Uri(@"Images/Folder1.png", UriKind.RelativeOrAbsolute);
                bi.EndInit();
                FilesIcon.Source = bi;
                UploadButton.Background = new SolidColorBrush(Colors.Green);
                UploadButton.IsEnabled = true;
            }
        }

19 View Source File : DteHelpers.cs
License : MIT License
Project Creator : aurelia

public static Project GetActiveProject(DTE2 dte)
        {
            try
            {
                if (dte.ActiveSolutionProjects is Array activeSolutionProjects && activeSolutionProjects.Length > 0)
                {
                    return activeSolutionProjects.GetValue(0) as Project;
                }

                var doc = dte.ActiveDoreplacedent;

                if (string.IsNullOrEmpty(doc?.FullName ?? null)) { return null; }
                var item = dte.Solution?.FindProjecreplacedem(doc.FullName);
                return item?.ContainingProject ?? null;
            }
            catch (Exception ex)
            {
                Logger.Log("Error getting the active project" + ex);
            }

            return null;
        }

19 View Source File : Watcher.cs
License : MIT License
Project Creator : aurelia

private Project getActiveProject()
        {
            Array projects = (Array)(Instance.DTE2.ActiveSolutionProjects ?? Instance.DTE2.Solution.SolutionBuild.StartupProjects);

            if (projects != null && projects.Length > 0)
            {
                if (projects.GetValue(0) is Project project)
                {
                    return project;
                }
            }

            Projects projs = Instance.DTE2.Solution.Projects;
            if (projs != null && projs.Count > 0)
            {
                return projs.Item(1);
            }
            return null;
        }

19 View Source File : JSEditor.cs
License : MIT License
Project Creator : Autodesk-Forge

public void InitDragDropFile()
    {

      TextArea.AllowDrop = true;
      TextArea.DragEnter += delegate (object sender, DragEventArgs e) {
        if (e.Data.GetDataPresent(DataFormats.FileDrop))
          e.Effect = DragDropEffects.Copy;
        else
          e.Effect = DragDropEffects.None;
      };
      TextArea.DragDrop += delegate (object sender, DragEventArgs e) {

        // get file drop
        if (e.Data.GetDataPresent(DataFormats.FileDrop))
        {

          Array a = (Array)e.Data.GetData(DataFormats.FileDrop);
          if (a != null)
          {

            string path = a.GetValue(0).ToString();

            LoadDataFromFile(path);

          }
        }
      };

    }

19 View Source File : ExpressionInterpreter.cs
License : GNU Lesser General Public License v2.1
Project Creator : axiom3d

void VisitArrayIndex (BinaryExpression binary)
		{
			Visit (binary.Left);
			var left = Pop ();
			Visit (binary.Right);
			var right = Pop ();

			Push (((Array) left).GetValue ((int) right));
		}

19 View Source File : ExpressionInterpreter.cs
License : GNU Lesser General Public License v2.1
Project Creator : axiom3d

static object GetDefaultValue (Type type)
		{
			var array = (Array) Array.CreateInstance (type, 1);
			return array.GetValue (0);
		}

19 View Source File : AyFuncManagementObject.cs
License : MIT License
Project Creator : ay2015

public string GetIPAddress()
        {
            string st = "";
            ManagementClreplaced mc = new ManagementClreplaced("Win32_NetworkAdapterConfiguration");
            ManagementObjectCollection moc = mc.GetInstances();
            foreach (ManagementObject mo in moc)
            {
                if ((bool)mo["IPEnabled"] == true)
                {
                    //st=mo["IpAddress"].ToString(); 
                    System.Array ar;
                    ar = (System.Array)(mo.Properties["IpAddress"].Value);
                    st = ar.GetValue(0).ToString();
                    break;
                }
            }
            return st;
        }

19 View Source File : SerializationUtils.cs
License : MIT License
Project Creator : azist

public static void WalkArrayWrite(Array arr, Action<object> each)
    {
      var rank = arr.Rank;

      if (rank==1)
      {
          var i = arr.GetLowerBound(0);
          var top = arr.GetUpperBound(0);
          for(; i<=top; i++)
            each(arr.GetValue(i));
          return;
      }


      var idxs = new int[rank];
      doDimensionGetValue(arr, idxs, 0, each);
    }

19 View Source File : SaveDuringPlay.cs
License : MIT License
Project Creator : azsumas

bool ScanFields(string fullName, Type type, ref object obj)
        {
            bool doneSomething = false;

            // Check if it's a complex type
            bool isLeaf = true;
            if (obj != null
                && !type.IsSubclreplacedOf(typeof(Component))
                && !type.IsSubclreplacedOf(typeof(GameObject)))
            {
                // Is it an array?
                if (type.IsArray)
                {
                    isLeaf = false;
                    Array array = obj as Array;
                    object arrayLength = array.Length;
                    if (OnLeafField != null && OnLeafField(
                            fullName + ".Length", arrayLength.GetType(), ref arrayLength))
                    {
                        Array newArray = Array.CreateInstance(
                                array.GetType().GetElementType(), Convert.ToInt32(arrayLength));
                        Array.Copy(array, 0, newArray, 0, Math.Min(array.Length, newArray.Length));
                        array = newArray;
                        doneSomething = true;
                    }
                    for (int i = 0; i < array.Length; ++i)
                    {
                        object element = array.GetValue(i);
                        if (ScanFields(fullName + "[" + i + "]", array.GetType().GetElementType(), ref element))
                        {
                            array.SetValue(element, i);
                            doneSomething = true;
                        }
                    }
                    if (doneSomething)
                        obj = array;
                }
                else
                {
                    // Check if it's a complex type
                    FieldInfo[] fields = obj.GetType().GetFields(bindingFlags);
                    if (fields.Length > 0)
                    {
                        isLeaf = false;
                        for (int i = 0; i < fields.Length; ++i)
                        {
                            string name = fullName + "." + fields[i].Name;
                            if (FilterField == null || FilterField(name, fields[i]))
                            {
                                object fieldValue = fields[i].GetValue(obj);
                                if (ScanFields(name, fields[i].FieldType, ref fieldValue))
                                {
                                    doneSomething = true;
                                    if (OnFieldValueChanged != null)
                                        OnFieldValueChanged(name, fields[i], obj, fieldValue);
                                }
                            }
                        }
                    }
                }
            }
            // If it's a leaf field then call the leaf handler
            if (isLeaf && OnLeafField != null)
                if (OnLeafField(fullName, type, ref obj))
                    doneSomething = true;

            return doneSomething;
        }

19 View Source File : SettingRecord.cs
License : MIT License
Project Creator : b-editor

private static object GetDefault(Type type)
        {
            if (type == typeof(bool)) return false;
            else if (type == typeof(byte)) return (byte)0;
            else if (type == typeof(sbyte)) return (sbyte)0;
            else if (type == typeof(short)) return (short)0;
            else if (type == typeof(ushort)) return (ushort)0;
            else if (type == typeof(int)) return 0;
            else if (type == typeof(uint)) return 0U;
            else if (type == typeof(long)) return 0L;
            else if (type == typeof(ulong)) return 0UL;
            else if (type == typeof(char)) return '\u200B';
            else if (type == typeof(double)) return 0D;
            else if (type == typeof(float)) return 0F;
            else if (type == typeof(string)) return string.Empty;
            else if (type == typeof(DateTime)) return DateTime.Now;
            else if (type == typeof(DateTimeOffset)) return DateTimeOffset.Now;
            else if (type == typeof(Guid)) return Guid.Empty;
            else if (type.IsEnum) return type.GetEnumValues().GetValue(0)!;
            else throw new NotSupportedException();
        }

See More Examples