System.Enum.GetValues(System.Type)

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

3430 Examples 7

19 Source : EnumExtensions.cs
with MIT License
from 17MKH

public static OptionCollectionResultModel ToResult<T>(bool ignoreUnKnown = false)
    {
        var enumType = typeof(T);

        if (!enumType.IsEnum)
            return null;

        if (ignoreUnKnown)
        {
            #region ==忽略UnKnown属性==

            if (!ListCacheNoIgnore.TryGetValue(enumType.TypeHandle, out OptionCollectionResultModel list))
            {
                var options = Enum.GetValues(enumType).Cast<Enum>()
                    .Where(m => !m.ToString().Equals("UnKnown"));

                list = Options2Collection(options);

                ListCacheNoIgnore.TryAdd(enumType.TypeHandle, list);
            }

            return list;

            #endregion ==忽略UnKnown属性==
        }
        else
        {
            #region ==包含UnKnown选项==

            if (!ListCache.TryGetValue(enumType.TypeHandle, out OptionCollectionResultModel list))
            {
                var options = Enum.GetValues(enumType).Cast<Enum>();
                list = Options2Collection(options);
                ListCache.TryAdd(enumType.TypeHandle, list);
            }

            return list;

            #endregion ==包含UnKnown选项==
        }
    }

19 Source : EnumExtensions.cs
with MIT License
from 17MKH

public static OptionCollectionResultModel ToResult(this Enum value, bool ignoreUnKnown = false)
    {
        var enumType = value.GetType();

        if (!enumType.IsEnum)
            return null;

        var options = Enum.GetValues(enumType).Cast<Enum>()
            .Where(m => !ignoreUnKnown || !m.ToString().Equals("UnKnown"));

        return Options2Collection(options);
    }

19 Source : ModuleCollection.cs
with MIT License
from 17MKH

private void LoadEnums(ModuleDescriptor descriptor)
    {
        var layer = descriptor.Layerreplacedemblies;

        if (layer.Core == null)
            return;

        var enumTypes = layer.Core.GetTypes().Where(m => m.IsEnum);
        foreach (var enumType in enumTypes)
        {
            var enumDescriptor = new ModuleEnumDescriptor
            {
                Name = enumType.Name,
                Type = enumType,
                Options = Enum.GetValues(enumType).Cast<Enum>().Where(m => !m.ToString().EqualsIgnoreCase("UnKnown")).Select(x => new OptionResultModel
                {
                    Label = x.ToDescription(),
                    Value = x
                }).ToList()
            };

            descriptor.EnumDescriptors.Add(enumDescriptor);
        }
    }

19 Source : BuildWindow.cs
with MIT License
from 1ZouLTReX1

static void KillAllProcesses()
    {
        foreach (GameLoopMode loopMode in Enum.GetValues(typeof(GameLoopMode)))
        {
            if (loopMode.Equals(GameLoopMode.Undefined))
                continue;

            var buildExe = GetBuildExe(loopMode);

            var processName = Path.GetFileNameWithoutExtension(buildExe);
            var processes = System.Diagnostics.Process.GetProcesses();
            foreach (var process in processes)
            {
                if (process.HasExited)
                    continue;

                try
                {
                    if (process.ProcessName != null && process.ProcessName == processName)
                    {
                        process.Kill();
                    }
                }
                catch (InvalidOperationException)
                {

                }
            }
        }
    }

19 Source : RandomHelper.cs
with MIT License
from 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 Source : RandomHelper.cs
with MIT License
from 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 Source : BuildUtils.cs
with MIT License
from 1ZouLTReX1

public static void KillAllProcesses()
    {
        foreach (GameLoopMode loopMode in Enum.GetValues(typeof(GameLoopMode)))
        {
            if (loopMode.Equals(GameLoopMode.Undefined))
                continue;

            var buildExe = GetBuildExe(loopMode);

            var processName = Path.GetFileNameWithoutExtension(buildExe);
            var processes = System.Diagnostics.Process.GetProcesses();

            foreach (var process in processes)
            {
                if (process.HasExited)
                    continue;

                try
                {
                    if (process.ProcessName != null && process.ProcessName == processName)
                    {
                        process.Kill();
                    }
                }
                catch (InvalidOperationException)
                {

                }
            }
        }
    }

19 Source : SlnItemsTest.cs
with MIT License
from 3F

[Theory]
        [MemberData(nameof(GetAnSlnItemsAll))]
        public void AllItemsTest2(SlnItems input, params SlnItems[] ignoring)
        {
            foreach(var item in Enum.GetValues(typeof(SlnItems)))
            {
                SlnItems v = (SlnItems)item;
                if(!input.HasFlag(v))
                {
                    bool failed = true;
                    foreach(var ignore in ignoring)
                    {
                        if(v.HasFlag(ignore))
                        {
                            failed = false;
                            break;
                        }
                    }

                    if(failed)
                    {
                        replacedert.False(true, $"`{input}` is not completed. Found `{v}`");
                    }
                }
            }
        }

19 Source : ItemManager.cs
with MIT License
from 404Lcc

public void ClearAllItems()
        {
            foreach (ItemType item in Enum.GetValues(typeof(ItemType)))
            {
                ClearItems(item);
            }
        }

19 Source : PanelManager.cs
with MIT License
from 404Lcc

public Panel[] OpenExceptPanels(PanelType[] types)
        {
            List<Panel> panelList = new List<Panel>();
            List<PanelType> typeList = new List<PanelType>(types);
            foreach (PanelType item in Enum.GetValues(typeof(PanelType)))
            {
                if (!typeList.Contains(item))
                {
                    panelList.Add(OpenPanel(item));
                }
            }
            return panelList.ToArray();
        }

19 Source : PanelManager.cs
with MIT License
from 404Lcc

public Panel[] OpenAllPanels()
        {
            List<Panel> panelList = new List<Panel>();
            foreach (PanelType item in Enum.GetValues(typeof(PanelType)))
            {
                panelList.Add(OpenPanel(item));
            }
            return panelList.ToArray();
        }

19 Source : PanelManager.cs
with MIT License
from 404Lcc

public Panel[] CloseExceptPanels(PanelType[] types)
        {
            List<Panel> panelList = new List<Panel>();
            List<PanelType> typeList = new List<PanelType>(types);
            foreach (PanelType item in Enum.GetValues(typeof(PanelType)))
            {
                if (!typeList.Contains(item))
                {
                    panelList.Add(ClosePanel(item));
                }
            }
            return panelList.ToArray();
        }

19 Source : PanelManager.cs
with MIT License
from 404Lcc

public Panel[] CloseAllPanels()
        {
            List<Panel> panelList = new List<Panel>();
            foreach (PanelType item in Enum.GetValues(typeof(PanelType)))
            {
                panelList.Add(ClosePanel(item));
            }
            return panelList.ToArray();
        }

19 Source : PanelManager.cs
with MIT License
from 404Lcc

public void ClearExceptPanels(PanelType[] types)
        {
            List<PanelType> typeList = new List<PanelType>(types);
            foreach (PanelType item in Enum.GetValues(typeof(PanelType)))
            {
                if (!typeList.Contains(item))
                {
                    ClearPanel(item);
                }
            }
        }

19 Source : PanelManager.cs
with MIT License
from 404Lcc

public void ClearAllPanels()
        {
            foreach (PanelType item in Enum.GetValues(typeof(PanelType)))
            {
                ClearPanel(item);
            }
        }

19 Source : TypeFuzzer.cs
with Apache License 2.0
from 42skillz

public T GenerateEnum<T>()
        {
            var enumValues = Enum.GetValues(typeof(T));
            return (T)enumValues.GetValue(_fuzzer.Random.Next(0, enumValues.Length));
        }

19 Source : TypeFuzzer.cs
with Apache License 2.0
from 42skillz

private object FuzzEnumValue(Type enumType)
        {
            var enumValues = Enum.GetValues(enumType);
            return enumValues.GetValue(_fuzzer.Random.Next(0, enumValues.Length));
        }

19 Source : NoDuplicationFuzzersShould.cs
with Apache License 2.0
from 42skillz

[Test]
        [Repeat(200)]
        public void Be_able_to_provide_always_different_values_of_MagnificentSeven_Enum()
        {
            var fuzzer = new Fuzzer(noDuplication: true);

            var maxNumberOfElements = Enum.GetValues(typeof(MagnificentSeven)).Length;
            CheckThatNoDuplicationIsMadeWhileGenerating<MagnificentSeven>(fuzzer, maxNumberOfElements, () =>
            {
                return fuzzer.GenerateEnum<MagnificentSeven>();
            });
        }

19 Source : NoDuplicationFuzzersShould.cs
with Apache License 2.0
from 42skillz

[Test]
        [Repeat(200)]
        public void Be_able_to_provide_always_different_values_of_MagnificentSeven_Enum_when_instantiating_from_fuzzer()
        {
            var fuzzer = new Fuzzer();

            var duplicationFuzzer = fuzzer.GenerateNoDuplicationFuzzer();

            var maxNumberOfElements = Enum.GetValues(typeof(MagnificentSeven)).Length;
            CheckThatNoDuplicationIsMadeWhileGenerating<MagnificentSeven>(duplicationFuzzer, maxNumberOfElements, () =>
            {
                return duplicationFuzzer.GenerateEnum<MagnificentSeven>();
            });
        }

19 Source : NoDuplicationFuzzersShould.cs
with Apache License 2.0
from 42skillz

[Test]
        [Repeat(200)]
        public void Be_able_to_provide_always_different_values_of_The_good_the_bad_and_the_ugly_Enum()
        {
            var fuzzer = new Fuzzer(noDuplication: true);

            var maxNumberOfElements = Enum.GetValues(typeof(TheGoodTheBadAndTheUgly)).Length;
            CheckThatNoDuplicationIsMadeWhileGenerating<TheGoodTheBadAndTheUgly>(fuzzer, maxNumberOfElements, () =>
            {
                return fuzzer.GenerateEnum<TheGoodTheBadAndTheUgly>();
            });
        }

19 Source : SuggestionsMade.cs
with Apache License 2.0
from 42skillz

private void InstantiateAnEmptyListForEveryPricingCategory()
        {
            foreach (PricingCategory pricingCategory in Enum.GetValues(typeof(PricingCategory)))
            {
                ForCategory[pricingCategory] = new List<SuggestionMade>();
            }
        }

19 Source : EnumExtensions.cs
with MIT License
from 52ABP

public static void Each(this Type enumType, Action<string, string, string> action)
        {
            if (enumType.BaseType != typeof (Enum))
            {
                return;
            }
            var arr = Enum.GetValues(enumType);
            foreach (var name in arr)
            {
                var value = (int) Enum.Parse(enumType, name.ToString());
                var fieldInfo = enumType.GetField(name.ToString());
                var description = "";
                if (fieldInfo != null)
                {
                    var attr = Attribute.GetCustomAttribute(fieldInfo,
                        typeof (DescriptionAttribute), false) as DescriptionAttribute;
                    if (attr != null)
                    {
                        description = attr.Description;
                    }
                }
                action(name.ToString(), value.ToString(), description);
            }
        }

19 Source : ExtendableEnums.cs
with MIT License
from 7ark

public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
    {
        currentProperty = property;
        ExtendEnumAttribute source = (ExtendEnumAttribute)attribute;
        System.Enum enumVal = GetBaseProperty<System.Enum>(property);

        enumNames = (property.enumDisplayNames).OfType<string>().ToList();
        if (source.display)
        {
            int[] enumValues = (int[])(System.Enum.GetValues(enumVal.GetType()));
            for (int i = 0; i < enumNames.Count; i++)
            {
                enumNames[i] += " | " + enumValues[i];
            }
        }

        EditorGUI.BeginProperty(position, label, property);
        if (!showWindow)
        {
            if (enumNames.Count != 0)
            {
                enumNames.Add("Add New...");
                int newValue = EditorGUI.Popup(position, property.displayName, property.intValue, enumNames.ToArray());

                if (newValue == enumNames.Count - 1)
                {
                    NewValuePopup popup = new NewValuePopup();
                    PopupWindow.Show(new Rect(Screen.width / 2 - popupWidth / 2, position.y - popupHeight / 2, 0, 0), popup);

                    newValueText = "";
                }
                else
                {
                    property.intValue = newValue;
                }
            }
            else
            {
                EditorGUI.LabelField(position, "Extendable Enums needs at least one value in your declared enum.");
            }
        }
        else
        {
            EditorGUI.LabelField(position, "Waiting for new value input.");
        }

        EditorGUI.EndProperty();
    }

19 Source : Utility.Enum.cs
with MIT License
from 7Bytes-Studio

public static void Foreach<T>(Action<T> foreachCallback) where T : struct, IComparable, IFormattable, IConvertible
            {
                var arr =  System.Enum.GetValues(typeof(T));
                foreach (T item in arr)
                {
                    if (null != foreachCallback)
                    {
                        foreachCallback.Invoke(item);
                    }
                }
            }

19 Source : MicroVM.Assembler.cs
with MIT License
from 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 Source : MicroVM.Assembler.cs
with MIT License
from 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 Source : Brain.cs
with Apache License 2.0
from A7ocin

public void UpdateCoreBrains()
    {

        // If CoreBrains is null, this means the Brain object was just 
        // instanciated and we create instances of each CoreBrain
        if (CoreBrains == null)
        {
            CoreBrains = new ScriptableObject[System.Enum.GetValues(typeof(BrainType)).Length];
            foreach (BrainType bt in System.Enum.GetValues(typeof(BrainType)))
            {
                CoreBrains[(int)bt] = ScriptableObject.CreateInstance("CoreBrain" + bt.ToString());
            }

        }
        else
        {
            foreach (BrainType bt in System.Enum.GetValues(typeof(BrainType)))
            {
                if ((int)bt >= CoreBrains.Length)
                    break;
                if (CoreBrains[(int)bt] == null)
                {
                    CoreBrains[(int)bt] = ScriptableObject.CreateInstance("CoreBrain" + bt.ToString());
                }
            }
        }

        // If the length of CoreBrains does not match the number of BrainTypes, 
        // we increase the length of CoreBrains
        if (CoreBrains.Length < System.Enum.GetValues(typeof(BrainType)).Length)
        {
            ScriptableObject[] new_CoreBrains = new ScriptableObject[System.Enum.GetValues(typeof(BrainType)).Length];
            foreach (BrainType bt in System.Enum.GetValues(typeof(BrainType)))
            {
                if ((int)bt < CoreBrains.Length)
                {
                    new_CoreBrains[(int)bt] = CoreBrains[(int)bt];
                }
                else
                {
                    new_CoreBrains[(int)bt] = ScriptableObject.CreateInstance("CoreBrain" + bt.ToString());
                }
            }
            CoreBrains = new_CoreBrains;
        }

        // If the stored instanceID does not match the current instanceID, 
        // this means that the Brain GameObject was duplicated, and
        // we need to make a new copy of each CoreBrain
        if (instanceID != gameObject.GetInstanceID())
        {
            foreach (BrainType bt in System.Enum.GetValues(typeof(BrainType)))
            {
                if (CoreBrains[(int)bt] == null)
                {
                    CoreBrains[(int)bt] = ScriptableObject.CreateInstance("CoreBrain" + bt.ToString());
                }
                else
                {
                    CoreBrains[(int)bt] = ScriptableObject.Instantiate(CoreBrains[(int)bt]);
                }
            }
            instanceID = gameObject.GetInstanceID();
        }

        // The coreBrain to display is the one defined in brainType
        coreBrain = (CoreBrain)CoreBrains[(int)brainType];

        coreBrain.SetBrain(this);
    }

19 Source : EnumCache.cs
with MIT License
from Abc-Arbitrage

public static EnumStrings Create(Type enumType)
            {
                var enumItems = Enum.GetValues(enumType)
                                    .Cast<Enum>()
                                    .Select(i => new EnumItem(i))
                                    .ToList();

                return ArrayEnumStrings.CanHandle(enumItems)
                    ? (EnumStrings)new ArrayEnumStrings(enumItems)
                    : new DictionaryEnumStrings(enumItems);
            }

19 Source : HandJointServiceInspector.cs
with Apache License 2.0
from abist-co-ltd

public override void DrawInspectorGUI(object target)
        {
            IMixedRealityHandJointService handJointService = (IMixedRealityHandJointService)target;

            EditorGUILayout.LabelField("Tracking State", EditorStyles.boldLabel);

            if (!Application.isPlaying)
            {
                GUI.color = disabledColor;
                EditorGUILayout.Toggle("Left Hand Tracked", false);
                EditorGUILayout.Toggle("Right Hand Tracked", false);
            }
            else
            {
                GUI.color = enabledColor;
                EditorGUILayout.Toggle("Left Hand Tracked", handJointService.IsHandTracked(Handedness.Left));
                EditorGUILayout.Toggle("Right Hand Tracked", handJointService.IsHandTracked(Handedness.Right));
            }

            GenerateHandJointLookup();

            GUI.color = enabledColor;
            EditorGUILayout.Space();
            EditorGUILayout.LabelField("Editor Settings", EditorStyles.boldLabel);
            ShowHandPreviewInSceneView = SessionState.GetBool(ShowHandPreviewInSceneViewKey, false);
            bool showHandPreviewInSceneView = EditorGUILayout.Toggle("Show Preview in Scene View", ShowHandPreviewInSceneView);
            if (ShowHandPreviewInSceneView != showHandPreviewInSceneView)
            {
                SessionState.SetBool(ShowHandPreviewInSceneViewKey, showHandPreviewInSceneView);
            }

            ShowHandJointFoldout = SessionState.GetBool(ShowHandJointFoldoutKey, false);
            ShowHandJointFoldout = EditorGUILayout.Foldout(ShowHandJointFoldout, "Visible Hand Joints", true);
            SessionState.SetBool(ShowHandJointFoldoutKey, ShowHandJointFoldout);

            if (ShowHandJointFoldout)
            {
                #region setting buttons

                EditorGUILayout.BeginHorizontal();

                if (GUILayout.Button("All"))
                {
                    foreach (TrackedHandJoint joint in Enum.GetValues(typeof(TrackedHandJoint)))
                    {
                        if (joint == TrackedHandJoint.None)
                        {
                            continue;
                        }

                        SessionState.SetBool(showHandJointSettingKeys[joint], true);
                        showHandJointSettings[joint] = true;
                    }
                }

                if (GUILayout.Button("Fingers"))
                {
                    foreach (TrackedHandJoint joint in Enum.GetValues(typeof(TrackedHandJoint)))
                    {
                        bool setting = false;
                        switch (joint)
                        {
                            case TrackedHandJoint.IndexTip:
                            case TrackedHandJoint.IndexDistalJoint:
                            case TrackedHandJoint.IndexKnuckle:
                            case TrackedHandJoint.IndexMetacarpal:
                            case TrackedHandJoint.IndexMiddleJoint:

                            case TrackedHandJoint.MiddleTip:
                            case TrackedHandJoint.MiddleDistalJoint:
                            case TrackedHandJoint.MiddleKnuckle:
                            case TrackedHandJoint.MiddleMetacarpal:
                            case TrackedHandJoint.MiddleMiddleJoint:

                            case TrackedHandJoint.PinkyTip:
                            case TrackedHandJoint.PinkyDistalJoint:
                            case TrackedHandJoint.PinkyKnuckle:
                            case TrackedHandJoint.PinkyMetacarpal:
                            case TrackedHandJoint.PinkyMiddleJoint:

                            case TrackedHandJoint.RingTip:
                            case TrackedHandJoint.RingDistalJoint:
                            case TrackedHandJoint.RingKnuckle:
                            case TrackedHandJoint.RingMetacarpal:
                            case TrackedHandJoint.RingMiddleJoint:

                            case TrackedHandJoint.ThumbTip:
                            case TrackedHandJoint.ThumbDistalJoint:
                            case TrackedHandJoint.ThumbMetacarpalJoint:
                            case TrackedHandJoint.ThumbProximalJoint:
                                setting = true;
                                break;

                            default:
                                break;

                            case TrackedHandJoint.None:
                                continue;
                        }

                        SessionState.SetBool(showHandJointSettingKeys[joint], setting);
                        showHandJointSettings[joint] = setting;
                    }
                }

                if (GUILayout.Button("Fingertips"))
                {
                    foreach (TrackedHandJoint joint in Enum.GetValues(typeof(TrackedHandJoint)))
                    {
                        bool setting = false;
                        switch (joint)
                        {
                            case TrackedHandJoint.IndexTip:
                            case TrackedHandJoint.MiddleTip:
                            case TrackedHandJoint.PinkyTip:
                            case TrackedHandJoint.RingTip:
                            case TrackedHandJoint.ThumbTip:
                                setting = true;
                                break;

                            default:
                                break;

                            case TrackedHandJoint.None:
                                continue;
                        }

                        SessionState.SetBool(showHandJointSettingKeys[joint], setting);
                        showHandJointSettings[joint] = setting;
                    }
                }

                if (GUILayout.Button("None"))
                {
                    foreach (TrackedHandJoint joint in Enum.GetValues(typeof(TrackedHandJoint)))
                    {
                        if (joint == TrackedHandJoint.None)
                        {
                            continue;
                        }

                        SessionState.SetBool(showHandJointSettingKeys[joint], false);
                        showHandJointSettings[joint] = false;
                    }
                }

                EditorGUILayout.EndHorizontal();

                #endregion

                EditorGUILayout.BeginVertical(EditorStyles.helpBox);
                foreach (TrackedHandJoint joint in Enum.GetValues(typeof(TrackedHandJoint)))
                {
                    if (joint == TrackedHandJoint.None)
                    {
                        continue;
                    }

                    bool prevSetting = showHandJointSettings[joint];
                    bool newSetting = EditorGUILayout.Toggle(joint.ToString(), prevSetting);
                    if (newSetting != prevSetting)
                    {
                        SessionState.SetBool(showHandJointSettingKeys[joint], newSetting);
                        showHandJointSettings[joint] = newSetting;
                    }
                }
                EditorGUILayout.EndVertical();
            }
        }

19 Source : HandJointServiceInspector.cs
with Apache License 2.0
from abist-co-ltd

private static void GenerateHandJointLookup()
        {
            if (showHandJointSettings != null)
            {
                return;
            }

            showHandJointSettingKeys = new Dictionary<TrackedHandJoint, string>();
            showHandJointSettings = new Dictionary<TrackedHandJoint, bool>();

            foreach (TrackedHandJoint joint in Enum.GetValues(typeof(TrackedHandJoint)))
            {
                if (joint == TrackedHandJoint.None)
                {
                    continue;
                }

                string key = ShowHandJointKeyPrefix + joint;
                showHandJointSettingKeys.Add(joint, key);

                bool showHandJoint = SessionState.GetBool(key, true);
                showHandJointSettings.Add(joint, showHandJoint);
            }
        }

19 Source : DialogShell.cs
with Apache License 2.0
from abist-co-ltd

protected override void GenerateButtons()
        {
            // Get List of ButtonTypes that should be created on Dialog
            List<DialogButtonType> buttonTypes = new List<DialogButtonType>();
            foreach (DialogButtonType buttonType in Enum.GetValues(typeof(DialogButtonType)))
            {
                // If this button type flag is set
                if (buttonType != DialogButtonType.None && result.Buttons.HasFlag(buttonType))
                {
                    buttonTypes.Add(buttonType);
                }
            }

            twoButtonSet = new GameObject[2];

            // Find all buttons on dialog...
            List<DialogButton> buttonsOnDialog = GetAllDialogButtons();

            // Set desired buttons active and the rest inactive
            SetButtonsActiveStates(buttonsOnDialog, buttonTypes.Count);

            // Set replacedles and types
            if (buttonTypes.Count > 0)
            {
                // If we have two buttons then do step 1, else 0
                int step = buttonTypes.Count >= 2 ? 1 : 0;
                for (int i = 0; i < buttonTypes.Count && i < 2; ++i)
                {
                    twoButtonSet[i] = buttonsOnDialog[i + step].gameObject;
                    buttonsOnDialog[i + step].Setreplacedle(buttonTypes[i].ToString());
                    buttonsOnDialog[i + step].ButtonTypeEnum = buttonTypes[i];
                }
            }
        }

19 Source : UwpAppxBuildTools.cs
with Apache License 2.0
from abist-co-ltd

private static void UpdateDependenciesElement(XElement dependencies, XNamespace defaultNamespace)
        {
            var values = (PlayerSettings.WSATargetFamily[])Enum.GetValues(typeof(PlayerSettings.WSATargetFamily));

            if (string.IsNullOrWhiteSpace(EditorUserBuildSettings.wsaUWPSDK))
            {
                var windowsSdkPaths = Directory.GetDirectories(@"C:\Program Files (x86)\Windows Kits\10\Lib");

                for (int i = 0; i < windowsSdkPaths.Length; i++)
                {
                    windowsSdkPaths[i] = windowsSdkPaths[i].Substring(windowsSdkPaths[i].LastIndexOf(@"\", StringComparison.Ordinal) + 1);
                }

                EditorUserBuildSettings.wsaUWPSDK = windowsSdkPaths[windowsSdkPaths.Length - 1];
            }

            string maxVersionTested = EditorUserBuildSettings.wsaUWPSDK;

            if (string.IsNullOrWhiteSpace(EditorUserBuildSettings.wsaMinUWPSDK))
            {
                EditorUserBuildSettings.wsaMinUWPSDK = UwpBuildDeployPreferences.MIN_PLATFORM_VERSION.ToString();
            }

            string minVersion = EditorUserBuildSettings.wsaMinUWPSDK;

            // Clear any we had before.
            dependencies.RemoveAll();

            foreach (PlayerSettings.WSATargetFamily family in values)
            {
                if (PlayerSettings.WSA.GetTargetDeviceFamily(family))
                {
                    dependencies.Add(
                        new XElement(defaultNamespace + "TargetDeviceFamily",
                        new XAttribute("Name", $"Windows.{family}"),
                        new XAttribute("MinVersion", minVersion),
                        new XAttribute("MaxVersionTested", maxVersionTested)));
                }
            }

            if (!dependencies.HasElements)
            {
                dependencies.Add(
                    new XElement(defaultNamespace + "TargetDeviceFamily",
                    new XAttribute("Name", "Windows.Universal"),
                    new XAttribute("MinVersion", minVersion),
                    new XAttribute("MaxVersionTested", maxVersionTested)));
            }
        }

19 Source : PointerUtils.cs
with Apache License 2.0
from abist-co-ltd

public static void SetGazePointerBehavior(PointerBehavior pointerBehavior)
        {
            if (CoreServices.InputSystem.FocusProvider is IPointerPreferences pointerPreferences)
            {
                pointerPreferences.GazePointerBehavior = pointerBehavior;
                foreach (InputSourceType sourceType in Enum.GetValues(typeof(InputSourceType)))
                {
                    pointerPreferences.SetPointerBehavior<GGVPointer>(Handedness.Any, sourceType, pointerBehavior);
                }
            }
            else
            {
                WarnAboutSettingCustomPointerBehaviors();
            }
        }

19 Source : PointerUtils.cs
with Apache License 2.0
from abist-co-ltd

public static void SetPointerBehavior<T>(PointerBehavior pointerBehavior, Handedness handedness = Handedness.Any) where T : clreplaced, IMixedRealityPointer
        {
            foreach (InputSourceType type in Enum.GetValues(typeof(InputSourceType)))
            {
                SetPointerBehavior<T>(pointerBehavior, type, handedness);
            }
        }

19 Source : CalculaValor.cs
with MIT License
from abrandaol-youtube

public void DefineValor(Pizza pizza)
        {
            var totalIngradientes = Enum.GetValues(typeof(IngredientesType)).Cast<Enum>().Count(pizza.IngredientesType.HasFlag);

            /*
             *  Expressão apra calculo do valor total da pizza
             *
             *  (Total de Ingradientes x R$ 1,70) + ( o tamanho da pizza x R$ 10,00) + (se for doce mais R$ 10,00) +
             *  (Se a borda for de chocolate é o tamanho da borda x R$ 5,00 e se for salgada x R$ 2,00)             
             */
            var valorIngredintes = totalIngradientes * 1.70;
            var valorTamanho = (int)pizza.PizzaSize * 10;
            var valorTipo = pizza.PizzaType == PizzaType.Doce ? 10 : 0;

            var valorBorda = 0;

            if (pizza.Borda != null)
            {
                valorBorda = pizza.Borda.BordaType == BordaType.Chocolate
                    ? (5 * (int)pizza.Borda.BordaSize)
                    : (2 * (int)pizza.Borda.BordaSize);
            }

            pizza.Valor = valorIngredintes + valorTamanho + valorTipo + valorBorda;
        }

19 Source : OVRProjectConfigEditor.cs
with MIT License
from absurd-joy

public static void DrawTargetDeviceInspector(OVRProjectConfig projectConfig)
	{
		bool hasModified = false;

		// Target Devices
		EditorGUILayout.LabelField("Target Devices", EditorStyles.boldLabel);

		foreach (OVRProjectConfig.DeviceType deviceType in System.Enum.GetValues(typeof(OVRProjectConfig.DeviceType)))
		{
			bool oldSupportsDevice = projectConfig.targetDeviceTypes.Contains(deviceType);
			bool newSupportsDevice = oldSupportsDevice;
			OVREditorUtil.SetupBoolField(projectConfig, ObjectNames.NicifyVariableName(deviceType.ToString()), ref newSupportsDevice, ref hasModified);

			if (newSupportsDevice && !oldSupportsDevice)
			{
				projectConfig.targetDeviceTypes.Add(deviceType);
			}
			else if (oldSupportsDevice && !newSupportsDevice)
			{
				projectConfig.targetDeviceTypes.Remove(deviceType);
			}
		}

		if (hasModified)
		{
			OVRProjectConfig.CommitProjectConfig(projectConfig);
		}
	}

19 Source : Generator.cs
with Apache License 2.0
from 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 Source : EnumHelper.cs
with GNU Affero General Public License v3.0
from ACEmulator

public static List<Enum> GetFlags(this Enum e)
        {
            return Enum.GetValues(e.GetType()).Cast<Enum>().Where(e.HasFlag).ToList();
        }

19 Source : Extensions.cs
with MIT License
from ACBrNet

public static void EnumDataSource<T>(this ComboBox cmb, T? valorPadrao = null) where T : struct
		{
			Guard.Against<ArgumentException>(!typeof(T).IsEnum, "O tipo precisar ser um Enum.");

			cmb.DataSource = Enum.GetValues(typeof(T));
			if (valorPadrao.HasValue) cmb.SelectedItem = valorPadrao.Value;
		}

19 Source : CommandParameterHelpers.cs
with GNU Affero General Public License v3.0
from ACEmulator

public static bool ResolveACEParameters(Session session, IEnumerable<string> aceParsedParameters, IEnumerable<ACECommandParameter> parameters, bool rawIncluded = false)
        {
            string parameterBlob = "";
            if (rawIncluded)
            {
                parameterBlob = aceParsedParameters.First();
            }
            else
            {
                parameterBlob = aceParsedParameters.Count() > 0 ? aceParsedParameters.Aggregate((a, b) => a + " " + b).Trim(new char[] { ' ', ',' }) : string.Empty;
            }
            int commaCount = parameterBlob.Count(x => x == ',');

            List<ACECommandParameter> acps = parameters.ToList();
            for (int i = acps.Count - 1; i > -1; i--)
            {
                ACECommandParameter acp = acps[i];
                acp.ParameterNo = i + 1;
                if (parameterBlob.Length > 0)
                {
                    try
                    {
                        switch (acp.Type)
                        {
                            case ACECommandParameterType.PositiveLong:
                                Match match4 = Regex.Match(parameterBlob, @"(-?\d+)$", RegexOptions.IgnoreCase);
                                if (match4.Success)
                                {
                                    if (!long.TryParse(match4.Groups[1].Value, out long val))
                                    {
                                        return false;
                                    }
                                    if (val <= 0)
                                    {
                                        return false;
                                    }
                                    acp.Value = val;
                                    acp.Defaulted = false;
                                    parameterBlob = (match4.Groups[1].Index == 0) ? string.Empty : parameterBlob.Substring(0, match4.Groups[1].Index).Trim(new char[] { ' ' });
                                }
                                break;
                            case ACECommandParameterType.Long:
                                Match match3 = Regex.Match(parameterBlob, @"(-?\d+)$", RegexOptions.IgnoreCase);
                                if (match3.Success)
                                {
                                    if (!long.TryParse(match3.Groups[1].Value, out long val))
                                    {
                                        return false;
                                    }
                                    acp.Value = val;
                                    acp.Defaulted = false;
                                    parameterBlob = (match3.Groups[1].Index == 0) ? string.Empty : parameterBlob.Substring(0, match3.Groups[1].Index).Trim(new char[] { ' ', ',' });
                                }
                                break;
                            case ACECommandParameterType.ULong:
                                Match match2 = Regex.Match(parameterBlob, @"(-?\d+)$", RegexOptions.IgnoreCase);
                                if (match2.Success)
                                {
                                    if (!ulong.TryParse(match2.Groups[1].Value, out ulong val))
                                    {
                                        return false;
                                    }
                                    acp.Value = val;
                                    acp.Defaulted = false;
                                    parameterBlob = (match2.Groups[1].Index == 0) ? string.Empty : parameterBlob.Substring(0, match2.Groups[1].Index).Trim(new char[] { ' ', ',' });
                                }
                                break;
                            case ACECommandParameterType.Location:
                                Position position = null;
                                Match match = Regex.Match(parameterBlob, @"([\d\.]+[ns])[^\d\.]*([\d\.]+[ew])$", RegexOptions.IgnoreCase);
                                if (match.Success)
                                {
                                    string ns = match.Groups[1].Value;
                                    string ew = match.Groups[2].Value;
                                    if (!TryParsePosition(new string[] { ns, ew }, out string errorMessage, out position))
                                    {
                                        if (session != null)
                                        {
                                            ChatPacket.SendServerMessage(session, errorMessage, ChatMessageType.Broadcast);
                                        }
                                        else
                                        {
                                            Console.WriteLine(errorMessage);
                                        }
                                        return false;
                                    }
                                    else
                                    {
                                        acp.Value = position;
                                        acp.Defaulted = false;
                                        int coordsStartPos = Math.Min(match.Groups[1].Index, match.Groups[2].Index);
                                        parameterBlob = (coordsStartPos == 0) ? string.Empty : parameterBlob.Substring(0, coordsStartPos).Trim(new char[] { ' ', ',' });
                                    }
                                }
                                break;
                            case ACECommandParameterType.OnlinePlayerName:
                                if (i != 0)
                                {
                                    throw new Exception("Player parameter must be the first parameter, since it can contain spaces.");
                                }
                                parameterBlob = parameterBlob.TrimEnd(new char[] { ' ', ',' });
                                Player targetPlayer = PlayerManager.GetOnlinePlayer(parameterBlob);
                                if (targetPlayer == null)
                                {
                                    string errorMsg = $"Unable to find player {parameterBlob}";
                                    if (session != null)
                                    {
                                        ChatPacket.SendServerMessage(session, errorMsg, ChatMessageType.Broadcast);
                                    }
                                    else
                                    {
                                        Console.WriteLine(errorMsg);
                                    }
                                    return false;
                                }
                                else
                                {
                                    acp.Value = targetPlayer;
                                    acp.Defaulted = false;
                                }
                                break;
                            case ACECommandParameterType.OnlinePlayerNameOrIid:
                                if (i != 0)
                                {
                                    throw new Exception("Player parameter must be the first parameter, since it can contain spaces.");
                                }

                                if (!parameterBlob.Contains(' '))
                                {
                                    if (uint.TryParse(parameterBlob, out uint iid))
                                    {
                                        Player targetPlayer2 = PlayerManager.GetOnlinePlayer(iid);
                                        if (targetPlayer2 == null)
                                        {
                                            string logMsg = $"Unable to find player with iid {iid}";
                                            if (session != null)
                                            {
                                                ChatPacket.SendServerMessage(session, logMsg, ChatMessageType.Broadcast);
                                            }
                                            else
                                            {
                                                Console.WriteLine(logMsg);
                                            }
                                            return false;
                                        }
                                        else
                                        {
                                            acp.Value = targetPlayer2;
                                            acp.Defaulted = false;
                                            break;
                                        }
                                    }
                                }
                                Player targetPlayer3 = PlayerManager.GetOnlinePlayer(parameterBlob);
                                if (targetPlayer3 == null)
                                {
                                    string logMsg = $"Unable to find player {parameterBlob}";
                                    if (session != null)
                                    {
                                        ChatPacket.SendServerMessage(session, logMsg, ChatMessageType.Broadcast);
                                    }
                                    else
                                    {
                                        Console.WriteLine(logMsg);
                                    }

                                    return false;
                                }
                                else
                                {
                                    acp.Value = targetPlayer3;
                                    acp.Defaulted = false;
                                }
                                break;
                            case ACECommandParameterType.OnlinePlayerIid:
                                Match matcha5 = Regex.Match(parameterBlob, /*((i == 0) ? "" : @"\s+") +*/ @"(\d{10})$|(0x[0-9a-f]{8})$", RegexOptions.IgnoreCase);
                                if (matcha5.Success)
                                {
                                    string strIid = "";
                                    if (matcha5.Groups[2].Success)
                                    {
                                        strIid = matcha5.Groups[2].Value;
                                    }
                                    else if (matcha5.Groups[1].Success)
                                    {
                                        strIid = matcha5.Groups[1].Value;
                                    }
                                    try
                                    {
                                        uint iid = 0;
                                        if (strIid.StartsWith("0x"))
                                        {
                                            iid = Convert.ToUInt32(strIid, 16);
                                        }
                                        else
                                        {
                                            iid = uint.Parse(strIid);
                                        }

                                        Player targetPlayer2 = PlayerManager.GetOnlinePlayer(iid);
                                        if (targetPlayer2 == null)
                                        {
                                            string logMsg = $"Unable to find player with iid {strIid}";
                                            if (session != null)
                                            {
                                                ChatPacket.SendServerMessage(session, logMsg, ChatMessageType.Broadcast);
                                            }
                                            else
                                            {
                                                Console.WriteLine(logMsg);
                                            }
                                            return false;
                                        }
                                        else
                                        {
                                            acp.Value = targetPlayer2;
                                            acp.Defaulted = false;
                                            parameterBlob = (matcha5.Groups[1].Index == 0) ? string.Empty : parameterBlob.Substring(0, matcha5.Groups[1].Index).Trim(new char[] { ' ', ',' });
                                        }
                                    }
                                    catch (Exception)
                                    {
                                        string errorMsg = $"Unable to parse {strIid} into a player iid";
                                        if (session != null)
                                        {
                                            ChatPacket.SendServerMessage(session, errorMsg, ChatMessageType.Broadcast);
                                        }
                                        else
                                        {
                                            Console.WriteLine(errorMsg);
                                        }
                                        return false;
                                    }
                                }
                                break;
                            case ACECommandParameterType.PlayerName:
                                if (i != 0)
                                {
                                    throw new Exception("Player name parameter must be the first parameter, since it can contain spaces.");
                                }
                                parameterBlob = parameterBlob.TrimEnd(new char[] { ' ', ',' });
                                if (string.IsNullOrWhiteSpace(parameterBlob))
                                {
                                    break;
                                }
                                else
                                {
                                    acp.Value = parameterBlob;
                                    acp.Defaulted = false;
                                }
                                break;
                            case ACECommandParameterType.Uri:
                                Match match5 = Regex.Match(parameterBlob, @"(https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*))$", RegexOptions.IgnoreCase);
                                if (match5.Success)
                                {
                                    string strUri = match5.Groups[1].Value;
                                    try
                                    {
                                        Uri url = new Uri(strUri);
                                        acp.Value = url;
                                        acp.Defaulted = false;
                                        parameterBlob = (match5.Groups[1].Index == 0) ? string.Empty : parameterBlob.Substring(0, match5.Groups[1].Index).Trim(new char[] { ' ', ',' });
                                    }
                                    catch (Exception)
                                    {
                                        return false;
                                    }
                                }
                                break;
                            case ACECommandParameterType.DoubleQuoteEnclosedText:
                                Match match6 = Regex.Match(parameterBlob.TrimEnd(), @"(\"".*\"")$", RegexOptions.IgnoreCase);
                                if (match6.Success)
                                {
                                    string txt = match6.Groups[1].Value;
                                    try
                                    {
                                        acp.Value = txt.Trim('"');
                                        acp.Defaulted = false;
                                        parameterBlob = (match6.Groups[1].Index == 0) ? string.Empty : parameterBlob.Substring(0, match6.Groups[1].Index).Trim(new char[] { ' ', ',' });
                                    }
                                    catch (Exception)
                                    {
                                        return false;
                                    }
                                }
                                break;
                            case ACECommandParameterType.CommaPrefixedText:
                                if (i == 0)
                                {
                                    throw new Exception("this parameter type is not appropriate as the first parameter");
                                }
                                if (i == acps.Count - 1 && !acp.Required && commaCount < acps.Count - 1)
                                {
                                    break;
                                }
                                Match match7 = Regex.Match(parameterBlob.TrimEnd(), @"\,\s*([^,]*)$", RegexOptions.IgnoreCase);
                                if (match7.Success)
                                {
                                    string txt = match7.Groups[1].Value;
                                    try
                                    {
                                        acp.Value = txt.TrimStart(new char[] { ' ', ',' });
                                        acp.Defaulted = false;
                                        parameterBlob = (match7.Groups[1].Index == 0) ? string.Empty : parameterBlob.Substring(0, match7.Groups[1].Index).Trim(new char[] { ' ', ',' });
                                    }
                                    catch (Exception)
                                    {
                                        return false;
                                    }
                                }
                                break;
                            case ACECommandParameterType.SimpleWord:
                                Match match8 = Regex.Match(parameterBlob.TrimEnd(), @"([a-zA-Z1-9_]+)\s*$", RegexOptions.IgnoreCase);
                                if (match8.Success)
                                {
                                    string txt = match8.Groups[1].Value;
                                    try
                                    {
                                        acp.Value = txt.TrimStart(' ');
                                        acp.Defaulted = false;
                                        parameterBlob = (match8.Groups[1].Index == 0) ? string.Empty : parameterBlob.Substring(0, match8.Groups[1].Index).Trim(new char[] { ' ', ',' });
                                    }
                                    catch (Exception)
                                    {
                                        return false;
                                    }
                                }
                                break;
                            case ACECommandParameterType.Enum:
                                if (acp.PossibleValues == null)
                                {
                                    throw new Exception("The enum parameter type must be accompanied by the PossibleValues");
                                }
                                if (!acp.PossibleValues.IsEnum)
                                {
                                    throw new Exception("PossibleValues must be an enum type");
                                }
                                Match match9 = Regex.Match(parameterBlob.TrimEnd(), @"([a-zA-Z1-9_]+)\s*$", RegexOptions.IgnoreCase);
                                if (match9.Success)
                                {
                                    string txt = match9.Groups[1].Value;
                                    try
                                    {
                                        txt = txt.Trim(new char[] { ' ', ',' });
                                        Array etvs = Enum.GetValues(acp.PossibleValues);
                                        foreach (object etv in etvs)
                                        {
                                            if (etv.ToString().ToLower() == txt.ToLower())
                                            {
                                                acp.Value = etv;
                                                acp.Defaulted = false;
                                                parameterBlob = (match9.Groups[1].Index == 0) ? string.Empty : parameterBlob.Substring(0, match9.Groups[1].Index).Trim(new char[] { ' ' });
                                                break;
                                            }
                                        }
                                    }
                                    catch (Exception)
                                    {
                                        return false;
                                    }
                                }
                                break;
                        }
                    }
                    catch
                    {
                        return false;
                    }
                }
                if (acp.Defaulted)
                {
                    acp.Value = acp.DefaultValue;
                }

                if (acp.Required && acp.Defaulted)
                {
                    if (!string.IsNullOrWhiteSpace(acp.ErrorMessage))
                    {
                        if (session != null)
                        {
                            ChatPacket.SendServerMessage(session, acp.ErrorMessage, ChatMessageType.Broadcast);
                        }
                        else
                        {
                            Console.WriteLine(acp.ErrorMessage);
                        }
                    }

                    return false;
                }
            }
            return true;
        }

19 Source : BodyPart.cs
with GNU Affero General Public License v3.0
from ACEmulator

public static List<BodyPart> GetFlags(BodyPart bodyParts)
        {
            return Enum.GetValues(typeof(BodyPart)).Cast<BodyPart>().Where(p => bodyParts.HasFlag(p)).ToList();
        }

19 Source : BodyPart.cs
with GNU Affero General Public License v3.0
from ACEmulator

public static List<CoverageMask> GetFlags(CoverageMask coverage)
        {
            return Enum.GetValues(typeof(CoverageMask)).Cast<CoverageMask>().Where(p => p != CoverageMask.Unknown && coverage.HasFlag(p)).ToList();
        }

19 Source : PacketHeaderFlagsUtil.cs
with GNU Affero General Public License v3.0
from ACEmulator

public static string UnfoldFlags(PacketHeaderFlags flags)
        {
            List<string> result = new List<string>();
            foreach (PacketHeaderFlags r in System.Enum.GetValues(typeof(PacketHeaderFlags)))
            {
                if ((flags & r) != 0)
                {
                    result.Add(r.ToString());
                }
            }
            return result.DefaultIfEmpty().Aggregate((a, b) => a + " | " + b);
        }

19 Source : WorldObject.cs
with GNU Affero General Public License v3.0
from ACEmulator

public Dictionary<PropertyInt, int?> GetProperties(WorldObject wo)
        {
            var props = new Dictionary<PropertyInt, int?>();

            var fields = Enum.GetValues(typeof(PropertyInt)).Cast<PropertyInt>();
            foreach (var field in fields)
            {
                var prop = wo.GetProperty(field);
                props.Add(field, prop);
            }
            return props;
        }

19 Source : MotionList.xaml.cs
with GNU General Public License v3.0
from ACEmulator

public void BuildMotionCommands()
        {
            MotionStances.Items.Clear();

            foreach (var motionStance in System.Enum.GetValues(typeof(MotionStance)))
                MotionStances.Items.Add(motionStance);

            MotionCommands.Items.Clear();

            foreach (var motionCommand in System.Enum.GetValues(typeof(MotionCommand)))
                MotionCommands.Items.Add(motionCommand);
        }

19 Source : DestructivePurgeViewModel.cs
with GNU Lesser General Public License v3.0
from acnicholas

public ObservableCollection<CheckableItem> GetPurgableItems()
        {
            var result = new ObservableCollection<CheckableItem>();
            var viewNotOnSheets = new CheckableItem(new DeletableItem("Views NOT On Sheets"), null);
            foreach (ViewType enumValue in Enum.GetValues(typeof(ViewType)))
            {
                if (enumValue == ViewType.DrawingSheet) {
                    continue;
                }
                var i = new CheckableItem(new DeletableItem(enumValue.ToString()), viewNotOnSheets);
                i.AddChildren(DestructivePurgeUtilitiles.Views(doc, false, enumValue));
                if (i.Children.Count > 0) {
                    viewNotOnSheets.AddChild(i);
                }
            }
            result.Add(viewNotOnSheets);

            var viewOnSheets = new CheckableItem(new DeletableItem("Views On Sheets"), null);
            foreach (ViewType enumValue in Enum.GetValues(typeof(ViewType)))
            {
                if (enumValue == ViewType.DrawingSheet) {
                    continue;
                }
                var i = new CheckableItem(new DeletableItem(enumValue.ToString()), viewOnSheets);
                i.AddChildren(DestructivePurgeUtilitiles.Views(doc, true, enumValue));
                if (i.Children.Count > 0) {
                    viewOnSheets.AddChild(i);
                }
            }
            result.Add(viewOnSheets);

            var sheets = new CheckableItem(new DeletableItem("Sheets"), null);
            sheets.AddChildren(DestructivePurgeUtilitiles.Views(doc, true, ViewType.DrawingSheet));
            result.Add(sheets);
            var images = new CheckableItem(new DeletableItem("Images"), null);
            images.AddChildren(DestructivePurgeUtilitiles.Images(doc));
            result.Add(images);
            var imports = new CheckableItem(new DeletableItem("CAD Imports"), null);
            imports.AddChildren(DestructivePurgeUtilitiles.Imports(doc, false));
            result.Add(imports);
            var links = new CheckableItem(new DeletableItem("CAD Links"), null);
            links.AddChildren(DestructivePurgeUtilitiles.Imports(doc, true));
            result.Add(links);
            var revisions = new CheckableItem(new DeletableItem("Revisions"), null);
            revisions.AddChildren(DestructivePurgeUtilitiles.Revisions(doc));
            result.Add(revisions);
            if (!isFamily)
            {
                var uvf = new CheckableItem(new DeletableItem("Unused View Filters"), null);
                uvf.AddChildren(DestructivePurgeUtilitiles.UnusedViewFilters(doc));
                result.Add(uvf);
            }
            var ubr = new CheckableItem(new DeletableItem("Unbound Rooms"), null);
            ubr.AddChildren(DestructivePurgeUtilitiles.UnboundRooms(doc));
            result.Add(ubr);
            return result;
        }

19 Source : UnknownEnumJsonConverter.cs
with MIT License
from actions

public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            // Newtonsoft doesn't call CanConvert if you specify the converter using a JsonConverter attribute
            // they just replacedume you know what you're doing :)
            if (!CanConvert(objectType))
            {
                // if there's no Unknown value, fall back to the StringEnumConverter behavior
                return base.ReadJson(reader, objectType, existingValue, serializer);
            }

            if (reader.TokenType == JsonToken.Integer)
            {
                var intValue = Convert.ToInt32(reader.Value);
                var values = (int[])Enum.GetValues(objectType);
                if (values.Contains(intValue))
                {
                    return Enum.Parse(objectType, intValue.ToString());
                }
            }

            if (reader.TokenType == JsonToken.String)
            {
                var stringValue = reader.Value.ToString();
                return UnknownEnum.Parse(objectType, stringValue);
            }

            // we know there's an Unknown value because CanConvert returned true
            return Enum.Parse(objectType, UnknownName);
        }

19 Source : KeyboardHookManager.cs
with MIT License
from adainrivers

public Guid RegisterHotkey(ModifierKeys modifiers, int virtualKeyCode, Func<Task> action)
        {
            var allModifiers = Enum.GetValues(typeof(ModifierKeys)).Cast<ModifierKeys>().ToArray();

            // Get the modifiers that were chained with bitwise OR operation as an array of modifiers
            var selectedModifiers = allModifiers.Where(modifier => modifiers.HasFlag(modifier)).ToArray();

            return RegisterHotkey(selectedModifiers, virtualKeyCode, action);
        }

19 Source : OutputTests.cs
with Apache License 2.0
from adamralph

[Fact]
        public static async Task Output()
        {
            // arrange
            using var output = new StringWriter();
            var ordinal = 1;

            // act
            foreach (var @bool in new[] { true, false })
            {
                await Write(output, noColor: true, noExtendedChars: !@bool, default, hostForced: @bool, default, skipDependencies: @bool, dryRun: @bool, parallel: @bool, verbose: true, new[] { "arg1", "arg2" }, ordinal++);
            }

            foreach (var noColor in new[] { true, false })
            {
                foreach (var host in (Host[])Enum.GetValues(typeof(Host)))
                {
                    foreach (var operatingSystem in (OperatingSystem[])Enum.GetValues(typeof(OperatingSystem)))
                    {
                        await Write(output, noColor, noExtendedChars: false, host, hostForced: true, operatingSystem, skipDependencies: true, dryRun: true, parallel: true, verbose: true, args: new List<string>(), ordinal++);
                    }
                }
            }

            // replacedert
            await replacedertFile.Contains("../../../output.txt", output.ToString().Replace(Environment.NewLine, "\r\n", StringComparison.Ordinal));
        }

19 Source : LoggingTest.cs
with MIT License
from adams85

[Fact]
        public async Task LoggingToMemoryWithoutDI()
        {
            foreach (LogFileAccessMode accessMode in Enum.GetValues(typeof(LogFileAccessMode)))
                await LoggingToMemoryWithoutDICore(accessMode);
        }

See More Examples