Here are the examples of the csharp api System.Enum.GetNames(System.Type) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
1027 Examples
19
Source : Options.cs
with MIT License
from BlackDragonBE
with MIT License
from BlackDragonBE
private void FillIconList()
{
cmbProfileImage.Items.AddRange(Enum.GetNames(typeof(ProfileImage)));
}
19
Source : Intelli.cs
with MIT License
from BoltBait
with MIT License
from BoltBait
internal static bool TryGetEnumNames(string enumName, out string[] names)
{
if (enumName == null || !(UserDefinedTypes.TryGetValue(enumName, out Type type) || AllTypes.TryGetValue(enumName, out type)) || !type.IsEnum)
{
names = null;
return false;
}
names = Enum.GetNames(type).Select(name => type.Name + "." + name).ToArray();
return true;
}
19
Source : EnumHelper.cs
with MIT License
from bonzajplc
with MIT License
from bonzajplc
public static string[] MaskOutEnumNames<TEnum>(int mask )
{
if (!typeof(TEnum).IsEnum) throw new ArgumentException("Arg not an enum");
var names = Enum.GetNames(typeof(TEnum));
var values = Enum.GetValues(typeof(TEnum));
var result = new List<String>();
for( int i = 0; i < values.Length; i++ )
{
if( ((int)values.GetValue(i) & mask ) != 0 )
result.Add( (string)names.GetValue(i) );
}
return result.ToArray();
}
19
Source : SettingsViewModel.cs
with GNU General Public License v3.0
from BornToBeRoot
with GNU General Public License v3.0
from BornToBeRoot
public void ChangeSettingsView(ApplicationName applicationName)
{
// Don't change the view, if the user has filtered the settings...
if (!string.IsNullOrEmpty(Search))
return;
if (System.Enum.GetNames(typeof(SettingsViewName)).Contains(applicationName.ToString()) && ApplicationName.None.ToString() != applicationName.ToString())
SelectedSettingsView = SettingsViews.SourceCollection.Cast<SettingsViewInfo>().FirstOrDefault(x => x.Name.ToString() == applicationName.ToString());
else
SelectedSettingsView = SettingsViews.SourceCollection.Cast<SettingsViewInfo>().FirstOrDefault(x => x.Name == SettingsViewName.General);
}
19
Source : AddCameraForm.cs
with GNU General Public License v2.0
from bp2008
with GNU General Public License v2.0
from bp2008
public void ConvertIntoEditForm(CameraDefinition existingCameraData)
{
newCamera = existingCameraData;
txtHostAndPort.Text = newCamera.hostAndPort;
txtUser.Text = newCamera.user;
txtPreplaced.Text = newCamera.preplaced;
cbHttps.Checked = newCamera.https;
txtDayZoom.Text = newCamera.dayZoom;
txtDayFocus.Text = newCamera.dayFocus;
txtNightZoom.Text = newCamera.nightZoom;
txtNightFocus.Text = newCamera.nightFocus;
nudLensCmdDelay.Value = newCamera.secondsBetweenLensCommands;
txtChannelNumbers.Text = newCamera.channelNumbers;
SetCbItems(cbSunriseProfile, Enum.GetNames(typeof(Profile)), newCamera.sunriseProfile);
SetCbItems(cbSunsetProfile, Enum.GetNames(typeof(Profile)), newCamera.sunsetProfile);
this.Text = "Edit Camera";
}
19
Source : BuildBundleID.cs
with Apache License 2.0
from bphillips09
with Apache License 2.0
from bphillips09
void Start() {
if (containerFlavor) {
string[] containerFlavors = System.Enum.GetNames (typeof(ContainerFlavor));
for(int i = 0; i < containerFlavors.Length; i++){
containerFlavor.options.Add (new Dropdown.OptionData () { text = containerFlavors [i] });
}
containerFlavor.value = 1;
}
if (region) {
string[] regions = System.Enum.GetNames (typeof(AzureRegion));
for(int i = 0; i < regions.Length; i++){
region.options.Add (new Dropdown.OptionData () { text = regions [i] });
}
region.value = 5;
}
if (vmSize) {
string[] vmSizes = System.Enum.GetNames (typeof(AzureVmSize));
for(int i = 0; i < vmSizes.Length; i++){
vmSize.options.Add (new Dropdown.OptionData () { text = vmSizes [i] });
}
vmSize.value = 7;
}
if (portProtocol) {
string[] portProtocols = System.Enum.GetNames (typeof(ProtocolType));
for(int i = 0; i < portProtocols.Length; i++){
portProtocol.options.Add (new Dropdown.OptionData () { text = portProtocols [i] });
}
portProtocol.value = 0;
}
}
19
Source : SettingsPage.cs
with MIT License
from brminnick
with MIT License
from brminnick
public Task SetTrendsChartOption(TrendsChartOption trendsChartOption)
{
var index = (int)trendsChartOption;
var totalRows = Enum.GetNames(typeof(TrendsChartOption)).Count();
return SelectFromPicker(index, totalRows, TrendsChartConstants.TrendsChartreplacedles[trendsChartOption], _preferredChartsPicker, _preferredChartsPickerContainer);
}
19
Source : SettingsPage.cs
with MIT License
from brminnick
with MIT License
from brminnick
public Task SelectTheme(PreferredTheme preferredTheme)
{
var index = (int)preferredTheme;
var totalRows = Enum.GetNames(typeof(PreferredTheme)).Count();
return SelectFromPicker(index, totalRows, preferredTheme.ToString(), _themePicker, _themePickerContainer);
}
19
Source : MultipleEntryPage.cs
with MIT License
from brminnick
with MIT License
from brminnick
public void EnterTextIntoAllEntrysUsingReturnButton(string text)
{
App.Tap(_defaultReturnTypeEntry);
for (int i = 0; i < Enum.GetNames(typeof(ReturnType)).Length; i++)
{
ClearThenEnterText(text);
App.PressEnter();
}
App.DismissKeyboard();
App.Screenshot($"Entered Text Into All Entrys Using Return Button: {text}");
}
19
Source : MobileSortingServiceTests.cs
with MIT License
from brminnick
with MIT License
from brminnick
public void CurrentOptionTest_InvalidOption()
{
//Arrange
SortingOption currentOption_Initial, currentOption_PlusOne, currentOption_NegativeOne;
var sortingService = ServiceCollection.ServiceProvider.GetRequiredService<MobileSortingService>();
//Act
currentOption_Initial = sortingService.CurrentOption;
sortingService.CurrentOption = (SortingOption)(Enum.GetNames(typeof(SortingOption)).Count() + 1);
currentOption_PlusOne = sortingService.CurrentOption;
sortingService.CurrentOption = (SortingOption)(-1);
currentOption_NegativeOne = sortingService.CurrentOption;
//replacedert
replacedert.AreEqual(MobileSortingService.DefaultSortingOption, currentOption_Initial);
replacedert.AreEqual(MobileSortingService.DefaultSortingOption, currentOption_PlusOne);
replacedert.AreEqual(MobileSortingService.DefaultSortingOption, currentOption_NegativeOne);
}
19
Source : SettingsViewModelTests.cs
with MIT License
from brminnick
with MIT License
from brminnick
[Test]
public void ThemePickerItemsSourceTest()
{
//Arrange
int themePickerIndex_Initial, themePickerIndex_AfterDarkTheme, themePickerIndex_AfterLightTheme, themePickerIndex_AfterDefaultTheme;
IReadOnlyList<string> themePickerItemSource_Initial, themePickerItemSource_Final;
var settingsViewModel = ServiceCollection.ServiceProvider.GetRequiredService<SettingsViewModel>();
//Act
themePickerItemSource_Initial = settingsViewModel.ThemePickerItemsSource;
themePickerIndex_Initial = settingsViewModel.ThemePickerSelectedIndex;
settingsViewModel.ThemePickerSelectedIndex = (int)PreferredTheme.Dark;
themePickerIndex_AfterDarkTheme = settingsViewModel.ThemePickerSelectedIndex;
settingsViewModel.ThemePickerSelectedIndex = (int)PreferredTheme.Light;
themePickerIndex_AfterLightTheme = settingsViewModel.ThemePickerSelectedIndex;
settingsViewModel.ThemePickerSelectedIndex = (int)PreferredTheme.Default;
themePickerIndex_AfterDefaultTheme = settingsViewModel.ThemePickerSelectedIndex;
themePickerItemSource_Final = settingsViewModel.ThemePickerItemsSource;
//replacedert
replacedert.AreEqual(Enum.GetNames(typeof(PreferredTheme)), themePickerItemSource_Initial);
replacedert.AreEqual(themePickerItemSource_Initial, themePickerItemSource_Final);
replacedert.AreEqual(PreferredTheme.Dark, (PreferredTheme)themePickerIndex_AfterDarkTheme);
replacedert.AreEqual(PreferredTheme.Light, (PreferredTheme)themePickerIndex_AfterLightTheme);
replacedert.AreEqual(PreferredTheme.Default, (PreferredTheme)themePickerIndex_AfterDefaultTheme);
}
19
Source : EntityToCrdExtensions.cs
with Apache License 2.0
from buehler
with Apache License 2.0
from buehler
private static V1JSONSchemaProps MapType(
Type type,
IList<V1CustomResourceColumnDefinition> additionalColumns,
string jsonPath)
{
var props = new V1JSONSchemaProps();
// this description is on the clreplaced
props.Description ??= type.GetCustomAttributes<DescriptionAttribute>(true).FirstOrDefault()?.Description;
var isSimpleType = IsSimpleType(type);
if (type == typeof(V1ObjectMeta))
{
props.Type = Object;
}
else if (type.IsArray)
{
props.Type = Array;
props.Items = MapType(
type.GetElementType() ?? throw new NullReferenceException("No Array Element Type found"),
additionalColumns,
jsonPath);
}
else if (!isSimpleType &&
(typeof(IDictionary).IsreplacedignableFrom(type) ||
(type.IsGenericType && type.GetGenericTypeDefinition() == typeof(IDictionary<,>)) ||
(type.IsGenericType &&
type.GetGenericArguments().FirstOrDefault()?.IsGenericType == true &&
type.GetGenericArguments().FirstOrDefault()?.GetGenericTypeDefinition() ==
typeof(KeyValuePair<,>))))
{
props.Type = Object;
props.XKubernetesPreserveUnknownFields = true;
}
else if (!isSimpleType && IsGenericEnumerableType(type, out Type? closingType))
{
props.Type = Array;
props.Items = MapType(closingType, additionalColumns, jsonPath);
}
else if (type == typeof(IntstrIntOrString))
{
props.XKubernetesIntOrString = true;
}
else if (typeof(IKubernetesObject).IsreplacedignableFrom(type) &&
!type.IsAbstract &&
!type.IsInterface &&
type.replacedembly == typeof(IKubernetesObject).replacedembly)
{
SetEmbeddedResourceProperties(props);
}
else if (!isSimpleType)
{
ProcessType(type, props, additionalColumns, jsonPath);
}
else if (type == typeof(int) || Nullable.GetUnderlyingType(type) == typeof(int))
{
props.Type = Integer;
props.Format = Int32;
}
else if (type == typeof(long) || Nullable.GetUnderlyingType(type) == typeof(long))
{
props.Type = Integer;
props.Format = Int64;
}
else if (type == typeof(float) || Nullable.GetUnderlyingType(type) == typeof(float))
{
props.Type = Number;
props.Format = Float;
}
else if (type == typeof(double) || Nullable.GetUnderlyingType(type) == typeof(double))
{
props.Type = Number;
props.Format = Double;
}
else if (type == typeof(string) || Nullable.GetUnderlyingType(type) == typeof(string))
{
props.Type = String;
}
else if (type == typeof(bool) || Nullable.GetUnderlyingType(type) == typeof(bool))
{
props.Type = Boolean;
}
else if (type == typeof(DateTime) || Nullable.GetUnderlyingType(type) == typeof(DateTime))
{
props.Type = String;
props.Format = DateTime;
}
else if (type.IsEnum)
{
props.Type = String;
props.EnumProperty = new List<object>(Enum.GetNames(type));
}
else if (Nullable.GetUnderlyingType(type)?.IsEnum == true)
{
props.Type = String;
props.EnumProperty = new List<object>(Enum.GetNames(Nullable.GetUnderlyingType(type)!));
}
else
{
throw new CrdPropertyTypeException();
}
return props;
}
19
Source : EntityToCrdExtensions.cs
with Apache License 2.0
from buehler
with Apache License 2.0
from buehler
private static V1JSONSchemaProps MapType(
Type type,
IList<V1CustomResourceColumnDefinition> additionalColumns,
string jsonPath)
{
var props = new V1JSONSchemaProps();
// this description is on the clreplaced
props.Description ??= type.GetCustomAttributes<DescriptionAttribute>(true).FirstOrDefault()?.Description;
var isSimpleType = IsSimpleType(type);
if (type == typeof(V1ObjectMeta))
{
props.Type = Object;
}
else if (type.IsArray)
{
props.Type = Array;
props.Items = MapType(
type.GetElementType() ?? throw new NullReferenceException("No Array Element Type found"),
additionalColumns,
jsonPath);
}
else if (!isSimpleType &&
(typeof(IDictionary).IsreplacedignableFrom(type) ||
(type.IsGenericType && type.GetGenericTypeDefinition() == typeof(IDictionary<,>)) ||
(type.IsGenericType &&
type.GetGenericArguments().FirstOrDefault()?.IsGenericType == true &&
type.GetGenericArguments().FirstOrDefault()?.GetGenericTypeDefinition() ==
typeof(KeyValuePair<,>))))
{
props.Type = Object;
props.XKubernetesPreserveUnknownFields = true;
}
else if (!isSimpleType && IsGenericEnumerableType(type, out Type? closingType))
{
props.Type = Array;
props.Items = MapType(closingType, additionalColumns, jsonPath);
}
else if (type == typeof(IntstrIntOrString))
{
props.XKubernetesIntOrString = true;
}
else if (typeof(IKubernetesObject).IsreplacedignableFrom(type) &&
!type.IsAbstract &&
!type.IsInterface &&
type.replacedembly == typeof(IKubernetesObject).replacedembly)
{
SetEmbeddedResourceProperties(props);
}
else if (!isSimpleType)
{
ProcessType(type, props, additionalColumns, jsonPath);
}
else if (type == typeof(int) || Nullable.GetUnderlyingType(type) == typeof(int))
{
props.Type = Integer;
props.Format = Int32;
}
else if (type == typeof(long) || Nullable.GetUnderlyingType(type) == typeof(long))
{
props.Type = Integer;
props.Format = Int64;
}
else if (type == typeof(float) || Nullable.GetUnderlyingType(type) == typeof(float))
{
props.Type = Number;
props.Format = Float;
}
else if (type == typeof(double) || Nullable.GetUnderlyingType(type) == typeof(double))
{
props.Type = Number;
props.Format = Double;
}
else if (type == typeof(string) || Nullable.GetUnderlyingType(type) == typeof(string))
{
props.Type = String;
}
else if (type == typeof(bool) || Nullable.GetUnderlyingType(type) == typeof(bool))
{
props.Type = Boolean;
}
else if (type == typeof(DateTime) || Nullable.GetUnderlyingType(type) == typeof(DateTime))
{
props.Type = String;
props.Format = DateTime;
}
else if (type.IsEnum)
{
props.Type = String;
props.EnumProperty = new List<object>(Enum.GetNames(type));
}
else if (Nullable.GetUnderlyingType(type)?.IsEnum == true)
{
props.Type = String;
props.EnumProperty = new List<object>(Enum.GetNames(Nullable.GetUnderlyingType(type)!));
}
else
{
throw new CrdPropertyTypeException();
}
return props;
}
19
Source : UI+Pickers.cs
with MIT License
from cabarius
with MIT License
from cabarius
public static void EnumGrid<TEnum>(Func<TEnum> get, Action<TEnum> set, int xCols, params GUILayoutOption[] options) where TEnum : struct {
var value = get();
var names = Enum.GetNames(typeof(TEnum));
var index = Array.IndexOf(names, value.ToString());
if (SelectionGrid(ref index, names, xCols, options)) {
if (Enum.TryParse(names[index], out TEnum newValue)) {
set(newValue);
}
}
}
19
Source : UI+Pickers.cs
with MIT License
from cabarius
with MIT License
from cabarius
public static bool EnumGrid<TEnum>(ref TEnum value, int xCols, Func<string, TEnum, string> replacedleFormater = null, GUIStyle style = null, params GUILayoutOption[] options) where TEnum : struct {
var changed = false;
options = options.AddDefaults();
var names = Enum.GetNames(typeof(TEnum));
var formatedNames = names;
var nameToEnum = value.NameToValueDictionary();
if (replacedleFormater != null)
formatedNames = names.Select((n) => replacedleFormater(n, nameToEnum[n])).ToArray();
var index = Array.IndexOf(names, value.ToString());
var oldIndex = index;
if (style == null ? SelectionGrid(ref index, formatedNames, xCols, options) : SelectionGrid(ref index, formatedNames, xCols, style, options)) {
if (Enum.TryParse(names[index], out TEnum newValue)) {
value = newValue;
changed = true;
}
}
return changed;
}
19
Source : ObjectExtensions.cs
with MIT License
from CacoCode
with MIT License
from CacoCode
[Description("枚举转换为字典")]
public static IDictionary<string, int> EnumToDictionary(this Type t)
{
if (t == null) throw new NullReferenceException();
if (!t.IsEnum) throw new InvalidCastException("object is not an Enumeration");
var names = Enum.GetNames(t);
var values = Enum.GetValues(t);
return (from i in Enumerable.Range(0, names.Length)
select new { Key = names[i], Value = (int)values.GetValue(i) }).ToDictionary(k => k.Key, k => k.Value);
}
19
Source : ApkExtractor.cs
with GNU General Public License v3.0
from canheo136
with GNU General Public License v3.0
from canheo136
private static Dictionary<string, Icon> createIconTable(List<int> positions, List<string> messages) {
if (positions.Count == 0 || messages.Count <= 2) // If dump failed
return new Dictionary<string, Icon>();
const char seperator = '\"';
// Prevent duplicate key when add to Dictionary,
// because comparison statement with 'hdpi' in config's values,
// reverse list and get first elem with LINQ
var configNames = Enum.GetNames(typeof(Configs)).Reverse();
var iconTable = new Dictionary<string, Icon>();
Action<string, string> addIcon2Table = (cfg, iconName) => {
if (!iconTable.ContainsKey(cfg)) {
iconTable.Add(cfg, new Icon(iconName));
}
};
string msg, resValue, config;
foreach (int index in positions) {
for (int i = index; ; i--) {
// Go prev to find config
msg = messages[i];
if (Detector.IsEntryType(msg)) // Out of entry and not found
break;
if (Detector.IsConfig(msg)) {
// Match with predefined configs,
// go next to get icon name
resValue = messages[index + 1];
config = configNames.FirstOrDefault(c => msg.Contains(c));
if (Detector.IsResourceValue(resValue)) {
// Resource value is icon url
var iconName = resValue.Split(seperator)
.FirstOrDefault(n => n.Contains("/"));
addIcon2Table(config, iconName);
break;
}
if(Detector.IsReference(resValue)) {
var iconID = resValue.Trim().Split(' ')[1];
addIcon2Table(config, iconID);
break;
}
break;
}
}
}
return iconTable;
}
19
Source : ApkExtractor.cs
with GNU General Public License v3.0
from canheo136
with GNU General Public License v3.0
from canheo136
private static Icon ExtractLargestIcon(Dictionary<string, Icon> iconTable) {
if (iconTable.Count == 0)
return Icon.Default;
var icon = Icon.Default;
var configNames = Enum.GetNames(typeof(Configs)).ToList();
configNames.Sort(new ConfigComparer());
foreach (string cfg in configNames) {
// Get the largest icon image, skip markup file (xml)
if (iconTable.TryGetValue(cfg, out icon)) {
if (icon.IconName.EndsWith(".xml", StringComparison.OrdinalIgnoreCase))
continue;
break; // Largest icon here :)
}
}
return icon ?? Icon.Default;
}
19
Source : CLRRedirections.cs
with MIT License
from CatLib
with MIT License
from CatLib
public static StackObject* EnumGetNames(ILIntepreter intp, StackObject* esp, IList<object> mStack, CLRMethod method, bool isNewObj)
{
var ret = esp - 1;
AppDomain domain = intp.AppDomain;
var p = esp - 1;
Type t = (Type)StackObject.ToObject(p, domain, mStack);
intp.Free(p);
if (t is ILRuntimeType)
{
ILType it = ((ILRuntimeType)t).ILType;
List<string> res = new List<string>();
if (it.IsEnum)
{
var fields = it.TypeDefinition.Fields;
for (int i = 0; i < fields.Count; i++)
{
var f = fields[i];
if (f.IsStatic)
{
res.Add(f.Name);
}
}
return ILIntepreter.PushObject(ret, mStack, res.ToArray(), true);
}
else
throw new Exception(string.Format("{0} is not Enum", t.FullName));
}
else if (t is ILRuntimeWrapperType)
{
return ILIntepreter.PushObject(ret, mStack, Enum.GetNames(((ILRuntimeWrapperType)t).RealType), true);
}
else
return ILIntepreter.PushObject(ret, mStack, Enum.GetNames(t), true);
}
19
Source : CLRRedirections.cs
with MIT License
from CatLib
with MIT License
from CatLib
public static StackObject* EnumGetNames(ILIntepreter intp, StackObject* esp, IList<object> mStack, CLRMethod method, bool isNewObj)
{
var ret = esp - 1;
AppDomain domain = intp.AppDomain;
var p = esp - 1;
Type t = (Type)StackObject.ToObject(p, domain, mStack);
intp.Free(p);
if (t is ILRuntimeType)
{
ILType it = ((ILRuntimeType)t).ILType;
List<string> res = new List<string>();
if (it.IsEnum)
{
var fields = it.TypeDefinition.Fields;
for (int i = 0; i < fields.Count; i++)
{
var f = fields[i];
if (f.IsStatic)
{
res.Add(f.Name);
}
}
return ILIntepreter.PushObject(ret, mStack, res.ToArray(), true);
}
else
throw new Exception(string.Format("{0} is not Enum", t.FullName));
}
else if (t is ILRuntimeWrapperType)
{
return ILIntepreter.PushObject(ret, mStack, Enum.GetNames(((ILRuntimeWrapperType)t).RealType), true);
}
else
return ILIntepreter.PushObject(ret, mStack, Enum.GetNames(t), true);
}
19
Source : TagViewModel.cs
with Apache License 2.0
from cdy816
with Apache License 2.0
from cdy816
private static void InitEnumType()
{
mTagTypeList = Enum.GetNames(typeof(Cdy.Tag.TagType));
mRecordTypeList = Enum.GetNames(typeof(Cdy.Tag.RecordType)).Select(e => Res.Get(e)).ToArray();
mReadWriteModeList = Enum.GetNames(typeof(Cdy.Tag.ReadWriteMode)).Select(e=>Res.Get(e)).ToArray();
}
19
Source : Utils.cs
with BSD 3-Clause "New" or "Revised" License
from celechii
with BSD 3-Clause "New" or "Revised" License
from celechii
public static int LengthOfEnum<TEnum>(this TEnum t)where TEnum : struct => System.Enum.GetNames(typeof(TEnum)).Length;
19
Source : InputManager.cs
with BSD 3-Clause "New" or "Revised" License
from celechii
with BSD 3-Clause "New" or "Revised" License
from celechii
private void Awake() {
control = this;
numKeyCodes = System.Enum.GetNames(typeof(KeyCode)).Length;
LoadKeyBinds();
BuildLookup();
}
19
Source : LumiProbesScript.cs
with MIT License
from cgaueb
with MIT License
from cgaueb
private ArrayList populatePlacementPopup() {
ArrayList options = new ArrayList();
options.AddRange(Enum.GetNames(typeof(PlacementType)));
if (!generatorListLightProbes.ContainsKey(PlacementType.NavMesh)) {
options.Remove(PlacementType.NavMesh.ToString());
options.Remove(PlacementType.NavMeshVolume.ToString());
if (LightProbesPlaceType == PlacementType.NavMesh || LightProbesPlaceType == PlacementType.NavMeshVolume) {
LightProbesPlaceType = PlacementType.Poisson;
}
if (EvaluationPositionsPlaceType == PlacementType.NavMesh || EvaluationPositionsPlaceType == PlacementType.NavMeshVolume) {
EvaluationPositionsPlaceType = PlacementType.Random;
}
}
return options;
}
19
Source : SDPSecurityDescription.cs
with MIT License
from chatop2020
with MIT License
from chatop2020
public static bool TryParse(string cryptoLine, out SDPSecurityDescription securityDescription)
{
securityDescription = null;
if (string.IsNullOrWhiteSpace(cryptoLine))
{
return false;
}
if (!cryptoLine.StartsWith(CRYPTO_ATTRIBUE_PREFIX))
{
throw new FormatException($"cryptoLine '{cryptoLine}' is not recognized as a valid SDP Security Description ");
}
string sCryptoValue = cryptoLine.Substring(cryptoLine.IndexOf(COLON) + 1);
securityDescription = new SDPSecurityDescription();
string[] sCryptoParts = sCryptoValue.Split(securityDescription.WHITE_SPACES, StringSplitOptions.RemoveEmptyEntries);
if (sCryptoValue.Length < 2)
{
throw new FormatException($"cryptoLine '{cryptoLine}' is not recognized as a valid SDP Security Description ");
}
try
{
securityDescription.Tag = uint.Parse(sCryptoParts[0]);
securityDescription.CryptoSuite = (from e in Enum.GetNames(typeof(CryptoSuites)) where e.CompareTo(sCryptoParts[1]) == 0 select (CryptoSuites)Enum.Parse(typeof(CryptoSuites), e)).FirstOrDefault();
if (securityDescription.CryptoSuite == CryptoSuites.unknown)
{
//this may not be a reason to return FALSE
//there might be a new crypto key used
}
string[] sKeyParams = sCryptoParts[2].Split(SEMI_COLON);
if (sKeyParams.Length < 1)
{
securityDescription = null;
return false;
}
foreach (string kp in sKeyParams)
{
KeyParameter keyParam = KeyParameter.Parse(kp, securityDescription.CryptoSuite);
securityDescription.KeyParams.Add(keyParam);
}
if (sCryptoParts.Length > 3)
{
securityDescription.SessionParam = SessionParameter.Parse(sCryptoParts[3], securityDescription.CryptoSuite);
}
return true;
}
catch
{
//catch all errors and throw own FormatException
}
return false;
}
19
Source : SDPSecurityDescription.cs
with MIT License
from chatop2020
with MIT License
from chatop2020
public static SessionParameter Parse(string sessionParam, CryptoSuites cryptoSuite = CryptoSuites.AES_CM_128_HMAC_SHA1_80)
{
if (string.IsNullOrWhiteSpace(sessionParam))
{
return null;
}
string p = sessionParam.Trim();
try
{
SessionParameter.SrtpSessionParams paramType = SrtpSessionParams.unknown;
if (p.StartsWith(KDR_PREFIX))
{
string sKdr = p.Substring(KDR_PREFIX.Length);
uint kdr = 0;
if (uint.TryParse(sKdr, out kdr))
{
return new SessionParameter(SrtpSessionParams.kdr) { Kdr = kdr };
}
}
else if (p.StartsWith(WSH_PREFIX))
{
string sWsh = p.Substring(WSH_PREFIX.Length);
uint wsh = 0;
if (uint.TryParse(sWsh, out wsh))
{
return new SessionParameter(SrtpSessionParams.wsh) { Wsh = wsh };
}
}
else if (p.StartsWith(FEC_KEY_PREFIX))
{
string sreplacedey = p.Substring(FEC_KEY_PREFIX.Length);
KeyParameter replacedey = KeyParameter.Parse(sreplacedey, cryptoSuite);
return new SessionParameter(SrtpSessionParams.fec_key) { replacedey = replacedey };
}
else if (p.StartsWith(FEC_ORDER_PREFIX))
{
string sFecOrder = p.Substring(FEC_ORDER_PREFIX.Length);
SessionParameter.FecTypes fecOrder = (from e in Enum.GetNames(typeof(FecTypes)) where e.CompareTo(sFecOrder) == 0 select (FecTypes)Enum.Parse(typeof(FecTypes), e)).FirstOrDefault();
if (fecOrder == FecTypes.unknown)
{
throw new FormatException($"sessionParam '{sessionParam}' is not recognized as a valid SRTP_SESSION_PARAM ");
}
return new SessionParameter(SrtpSessionParams.fec_order) { FecOrder = fecOrder };
}
else
{
paramType = (from e in Enum.GetNames(typeof(SrtpSessionParams)) where e.CompareTo(p) == 0 select (SrtpSessionParams)Enum.Parse(typeof(SrtpSessionParams), e)).FirstOrDefault();
if (paramType == SrtpSessionParams.unknown)
{
throw new FormatException($"sessionParam '{sessionParam}' is not recognized as a valid SRTP_SESSION_PARAM ");
}
switch (paramType)
{
case SrtpSessionParams.UNAUTHENTICATED_SRTP:
case SrtpSessionParams.UNENCRYPTED_SRTCP:
case SrtpSessionParams.UNENCRYPTED_SRTP:
return new SessionParameter(paramType);
}
}
}
catch
{
//catch all errors and throw own FormatException
}
throw new FormatException($"sessionParam '{sessionParam}' is not recognized as a valid SRTP_SESSION_PARAM ");
}
19
Source : SDPSecurityDescription.cs
with MIT License
from chatop2020
with MIT License
from chatop2020
public static SDPSecurityDescription Parse(string cryptoLine)
{
if (string.IsNullOrWhiteSpace(cryptoLine))
{
return null;
}
if (!cryptoLine.StartsWith(CRYPTO_ATTRIBUE_PREFIX))
{
throw new FormatException($"cryptoLine '{cryptoLine}' is not recognized as a valid SDP Security Description ");
}
string sCryptoValue = cryptoLine.Substring(cryptoLine.IndexOf(COLON) + 1);
SDPSecurityDescription sdpCryptoAttribute = new SDPSecurityDescription();
string[] sCryptoParts = sCryptoValue.Split(sdpCryptoAttribute.WHITE_SPACES, StringSplitOptions.RemoveEmptyEntries);
if (sCryptoValue.Length < 2)
{
throw new FormatException($"cryptoLine '{cryptoLine}' is not recognized as a valid SDP Security Description ");
}
try
{
sdpCryptoAttribute.Tag = uint.Parse(sCryptoParts[0]);
sdpCryptoAttribute.CryptoSuite = (from e in Enum.GetNames(typeof(CryptoSuites)) where e.CompareTo(sCryptoParts[1]) == 0 select (CryptoSuites)Enum.Parse(typeof(CryptoSuites), e)).FirstOrDefault();
if (sdpCryptoAttribute.CryptoSuite == CryptoSuites.unknown)
{
throw new FormatException($"cryptoLine '{cryptoLine}' is not recognized as a valid SDP Security Description ");
}
string[] sKeyParams = sCryptoParts[2].Split(SEMI_COLON);
if (sKeyParams.Length < 1)
{
throw new FormatException($"cryptoLine '{cryptoLine}' is not recognized as a valid SDP Security Description ");
}
foreach (string kp in sKeyParams)
{
KeyParameter keyParam = KeyParameter.Parse(kp, sdpCryptoAttribute.CryptoSuite);
sdpCryptoAttribute.KeyParams.Add(keyParam);
}
if (sCryptoParts.Length > 3)
{
sdpCryptoAttribute.SessionParam = SessionParameter.Parse(sCryptoParts[3], sdpCryptoAttribute.CryptoSuite);
}
return sdpCryptoAttribute;
}
catch
{
//catch all errors and throw own FormatException
}
throw new FormatException($"cryptoLine '{cryptoLine}' is not recognized as a valid SDP Security Description ");
}
19
Source : CheepsAmongUsMod.cs
with GNU General Public License v2.0
from CheepYT
with GNU General Public License v2.0
from CheepYT
public override void Load()
{
_logger = Log;
_logger.LogInfo($"{PluginName} v{PluginVersion} created by Cheep loaded");
RandomMapLocations.Add(MapType.Polus,
new Vector2[]
{
new Vector2(3, -12),
new Vector2(9, -12),
new Vector2(2, -17),
new Vector2(2, -24),
new Vector2(12, -23),
new Vector2(12, -16),
new Vector2(24, -22.5f),
new Vector2(20, -17.5f),
new Vector2(20, -11),
new Vector2(35, -8),
new Vector2(40, -10),
new Vector2(37, -21),
new Vector2(17, -3)
});
RandomMapLocations.Add(MapType.Skeld,
new Vector2[]
{
new Vector2(-1, -1),
new Vector2(-8.8f, -3),
new Vector2(-13.5f, -4.5f),
new Vector2(-20.5f, -6),
new Vector2(-17.5f, 2.5f),
new Vector2(-2, -15.5f),
new Vector2(9.4f, 2.8f),
new Vector2(9.4f, -12),
new Vector2(4, -15.5f),
new Vector2(-7.5f, -8.5f),
new Vector2(-15, -12),
new Vector2(6.5f, -3.5f),
new Vector2(16.5f, -5)
});
RandomMapLocations.Add(MapType.MiraHQ,
new Vector2[] {
new Vector2(-4, 2.5f),
new Vector2(15, 0),
new Vector2(6, 1.5f),
new Vector2(6, 6),
new Vector2(2.4f, 11.5f),
new Vector2(8.5f, 13),
new Vector2(15, 4),
new Vector2(20, 4.5f),
new Vector2(23.8f, -1.7f),
new Vector2(25.5f, 3),
new Vector2(17.7f, 11.5f),
new Vector2(21, 20.6f),
new Vector2(14.8f, 20.3f),
new Vector2(17.8f, 23.8f)
});
_logger.LogInfo("Enabling harmony");
#region ---------- Enable Harmony Patching ----------
var harmony = new Harmony(PluginGuid);
harmony.PatchAll(replacedembly.GetExecutingreplacedembly());
#endregion
_logger.LogInfo("Loading regions");
#region ---------- Add custom regions ----------
new Region(ServerName, ServerIP, new Server(ServerName, ServerIP, ServerPort)).InsertRegion(0); // Add Cheep-YT.com
string serversPath = $"BepInEx/plugins/{PluginName}/servers/"; // Path to servers
Directory.CreateDirectory(serversPath); // Create directory, if it does not exist
if (!File.Exists(serversPath + "README.txt")) // Create a readme, if it does not exist
{
File.AppendAllText(serversPath + "README.txt",
"This directory can be used to add additional servers.\r\n" +
"\r\n" +
"To add a server, create a .txt file and name it, how you want the server to be called.\r\n" +
"Within this file simply enter the ip adress and port like this:\r\n" +
"207.180.234.175:22023");
}
foreach (var file in Directory.GetFiles(serversPath).Where(x => !Path.GetFileName(x).Equals("README.txt") && x.EndsWith(".txt"))) // Get all files in directory
{
var server = File.ReadAllLines(file)[0].Split(':'); // Get the first line of the file
try
{
string ip = server[0]; // Get the servers ip
ushort port = ushort.Parse(server[1]); // Get the servers port
string name = Path.GetFileNameWithoutExtension(file); // Get the server name
new Region(name, ip, new Server(name, ip, port)).AddRegion(); // Add region
}
catch (Exception e)
{
_logger.LogError("Failed to parse server " + file + ": " + e);
}
}
#endregion
_logger.LogInfo("Setting up custom options");
#region ----------- Setup Custom Options -----------
HeaderNumberOption = new CustomNumberOption(Functions.ColorCyan + PluginName, new string[] { $"{GameMode.AvailableGameModes.Count - 1} Modes" });
GameModeNumberOption = new CustomNumberOption("GameMode", GameMode.ShortGameModeNames);
GameModeNumberOption.ValueChanged += GameModeManager.GameModeNumberOption_ValueChanged;
var mapObject = new CustomNumberOption("Map", Enum.GetNames(typeof(MapType)));
mapObject.ValueChanged += CustomNumberOption_ValueChanged; ;
mapObject.Value = (int)GameOptions.Map;
var impostorsObject = new CustomNumberOption("Impostor Count", new string[] { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10" });
impostorsObject.Value = 1;
impostorsObject.ValueChanged += CustomNumberOption_ValueChanged;
var maxPlayerObj = new CustomNumberOption("Max Players", new string[] { "4", "5", "10", "15", "20", "30", "50", "70", "100", "125" });
impostorsObject.Value = 2;
maxPlayerObj.ValueChanged += CustomNumberOption_ValueChanged;
#endregion
#region ---------- Update CustomNumberOptions ----------
LobbyBehaviourStartedEvent.Listener += () =>
{
CurrentButtonIndex = 0;
Task.Run(async () =>
{
await Task.Delay(2000);
mapObject.Value = (int)GameOptions.Map;
impostorsObject.Value = impostorsObject.ValueStrings.IndexOf(GameOptions.ImpostorCount.ToString());
maxPlayerObj.Value = maxPlayerObj.ValueStrings.IndexOf(GameOptions.MaxPlayers.ToString());
});
};
#endregion
_logger.LogInfo("Registering commands");
#region ---------- Register Commands ----------
new HelpCommand();
new GameOptionsCommand();
#endregion
SelectedGameMode = new GameMode(0, "Default");
GameModeManager.Start(); // Start GameModeManager
RoleManager.Start(); // Start RoleManager
RoleGameModeManager.Start(); // Start RoleGameModeManager
Notifier.StartNotifier(); // Start Notifier
if (Config.Bind("Debug", "enable_debug", true, "Enables the debug menu").Value)
DebugMenu.Start();
}
19
Source : ToonShaderGUI.cs
with MIT License
from ChiliMilk
with MIT License
from ChiliMilk
private void DrawSurfaceOptions(MaterialEditor materialEditor)
{
// Get Material
var material = materialEditor.target as Material;
// Workflow Mode
DoPopup(Styles.WorkflowMode, m_WorkflowModeProp, Enum.GetNames(typeof(WorkflowMode)),materialEditor);
//// Render Face
//if (material.HasProperty(MPropertyNames.Cull))
//{
// EditorGUI.showMixedValue = m_CullProp.hasMixedValue;
// EditorGUI.BeginChangeCheck();
// int renderFace = EditorGUILayout.Popup(Styles.RenderFace, (int)m_CullProp.floatValue, Enum.GetNames(typeof(RenderFace)));
// if (EditorGUI.EndChangeCheck())
// {
// materialEditor.RegisterPropertyChangeUndo(Styles.RenderFace.text);
// m_CullProp.floatValue = renderFace;
// material.doubleSidedGI = (RenderFace)m_CullProp.floatValue != RenderFace.Front;
// }
// EditorGUI.showMixedValue = false;
//}
if (material.HasProperty(MPropertyNames.SurfaceType))
{
EditorGUI.showMixedValue = m_SurfaceTypeProp.hasMixedValue;
EditorGUI.BeginChangeCheck();
var surface = EditorGUILayout.Popup(Styles.SurfaceType, (int)m_SurfaceTypeProp.floatValue, Enum.GetNames(typeof(SurfaceType)));
if (EditorGUI.EndChangeCheck())
{
materialEditor.RegisterPropertyChangeUndo(Styles.SurfaceType.text);
if ((SurfaceType)surface == SurfaceType.Opaque)
{
material.renderQueue = (int)UnityEngine.Rendering.RenderQueue.Geometry;
}
else
{
material.renderQueue = (int)UnityEngine.Rendering.RenderQueue.Transparent;
}
m_RenderQueueProp.floatValue = material.renderQueue;
m_SurfaceTypeProp.floatValue = surface;
}
EditorGUI.showMixedValue = false;
}
// Render Face
if (material.HasProperty(MPropertyNames.Cull))
{
if ((SurfaceType)material.GetFloat(MPropertyNames.SurfaceType) == SurfaceType.Opaque)
{
EditorGUI.showMixedValue = m_CullProp.hasMixedValue;
EditorGUI.BeginChangeCheck();
int renderFace = EditorGUILayout.Popup(Styles.RenderFace, (int)m_CullProp.floatValue, Enum.GetNames(typeof(RenderFace)));
if (EditorGUI.EndChangeCheck())
{
materialEditor.RegisterPropertyChangeUndo(Styles.RenderFace.text);
m_CullProp.floatValue = renderFace;
material.doubleSidedGI = (RenderFace)m_CullProp.floatValue != RenderFace.Front;
}
EditorGUI.showMixedValue = false;
}
else
{
m_CullProp.floatValue = (float)RenderFace.Front;
material.doubleSidedGI = false;
}
}
// AlphaClip
if (material.HasProperty(MPropertyNames.AlphaClip) && material.HasProperty(MPropertyNames.Cutoff))
{
EditorGUI.BeginChangeCheck();
var enableAlphaClip = EditorGUILayout.Toggle(Styles.AlphaClipping, m_AlphaClipProp.floatValue == 1);
if (EditorGUI.EndChangeCheck())
{
m_AlphaClipProp.floatValue = enableAlphaClip ? 1 : 0;
m_RenderQueueProp.floatValue = enableAlphaClip ? (int)UnityEngine.Rendering.RenderQueue.AlphaTest : (int)UnityEngine.Rendering.RenderQueue.Geometry;
}
if (m_AlphaClipProp.floatValue == 1)
{
materialEditor.ShaderProperty(m_InverseClipMaskProp, Styles.InverseClipMask);
materialEditor.TexturePropertySingleLine(Styles.AlphaClippingMask, m_ClipMaskProp, m_CutoffProp);
}
}
//Stencil
if (material.HasProperty(MPropertyNames.EnableStencil) && material.HasProperty(MPropertyNames.StencilChannel))
{
EditorGUI.BeginChangeCheck();
var enableStencil = EditorGUILayout.Toggle(Styles.EnableStencil, m_EnableStencilProp.floatValue == 1);
if (EditorGUI.EndChangeCheck())
{
m_EnableStencilProp.floatValue = enableStencil ? 1 : 0;
}
if (m_EnableStencilProp.floatValue == 1)
{
EditorGUI.showMixedValue = m_StencilTypeProp.hasMixedValue;
EditorGUI.BeginChangeCheck();
var stencilType = EditorGUILayout.Popup(Styles.StencilType, (int)m_StencilTypeProp.floatValue, Enum.GetNames(typeof(StencilType)));
if (EditorGUI.EndChangeCheck())
{
materialEditor.RegisterPropertyChangeUndo(Styles.StencilType.text);
m_StencilTypeProp.floatValue = stencilType;
if (m_StencilTypeProp.floatValue == 0)
{
material.SetInt("_StencilComp", (int)UnityEngine.Rendering.CompareFunction.Always);
material.SetInt("_StencilOp", (int)UnityEngine.Rendering.StencilOp.Replace);
}
else if (m_StencilTypeProp.floatValue == 1)
{
material.SetInt("_StencilComp", (int)UnityEngine.Rendering.CompareFunction.NotEqual);
material.SetInt("_StencilOp", (int)UnityEngine.Rendering.StencilOp.Keep);
}
}
materialEditor.ShaderProperty(m_StencilChannelProp, Styles.StencilChannel);
EditorGUI.showMixedValue = false;
}
else
{
material.SetInt("_StencilComp", (int)UnityEngine.Rendering.CompareFunction.Disabled);
material.SetInt("_StencilOp", (int)UnityEngine.Rendering.StencilOp.Keep);
}
}
}
19
Source : TestRunnerWindow.cs
with MIT License
from chstetco
with MIT License
from chstetco
public void OnGUI()
{
if (!m_Enabled)
{
Enable();
}
if (BuildPipeline.isBuildingPlayer)
{
m_IsBuilding = true;
}
else if (m_IsBuilding)
{
m_IsBuilding = false;
Repaint();
}
EditorGUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
var selectedIndex = m_TestTypeToolbarIndex;
m_TestTypeToolbarIndex = GUILayout.Toolbar(m_TestTypeToolbarIndex, Enum.GetNames(typeof(TestRunnerMenuLabels)), "LargeButton", UnityEngine.GUI.ToolbarButtonSize.FitToContents);
GUILayout.FlexibleSpace();
EditorGUILayout.EndHorizontal();
if (selectedIndex != m_TestTypeToolbarIndex)
{
SelectTestListGUI(m_TestTypeToolbarIndex);
StartRetrieveTestList();
}
EditorGUILayout.BeginVertical();
using (new EditorGUI.DisabledScope(EditorApplication.isPlayingOrWillChangePlaymode))
{
m_SelectedTestTypes.PrintHeadPanel();
}
EditorGUILayout.EndVertical();
if (m_Settings.verticalSplit)
SplitterGUILayout.BeginVerticalSplit(m_Spl);
else
SplitterGUILayout.BeginHorizontalSplit(m_Spl);
EditorGUILayout.BeginVertical();
EditorGUILayout.BeginVertical(Styles.testList);
m_SelectedTestTypes.RenderTestList();
EditorGUILayout.EndVertical();
EditorGUILayout.EndVertical();
m_SelectedTestTypes.RenderDetails();
if (m_Settings.verticalSplit)
SplitterGUILayout.EndVerticalSplit();
else
SplitterGUILayout.EndHorizontalSplit();
}
19
Source : PinHelp.cs
with MIT License
from chucklenugget
with MIT License
from chucklenugget
void OnPinHelpCommand(User user)
{
var sb = new StringBuilder();
sb.AppendLine("Available commands:");
sb.AppendLine(" <color=#ffd479>/pin list [TYPE]</color>: List all pins (or all of a certain type)");
sb.AppendLine(" <color=#ffd479>/pin add TYPE \"NAME\"</color>: Create a pin at your current location");
sb.AppendLine(" <color=#ffd479>/pin remove \"NAME\"</color>: Remove a pin you created");
sb.AppendLine(" <color=#ffd479>/pin help</color>: Prints this message");
if (user.HasPermission(Permission.AdminPins))
{
sb.AppendLine("Admin commands:");
sb.AppendLine(" <color=#ffd479>/pin delete XY</color>: Delete a pin from an area");
}
sb.Append("Available pin types: ");
foreach (string type in Enum.GetNames(typeof(PinType)).OrderBy(str => str.ToLowerInvariant()))
sb.AppendFormat("<color=#ffd479>{0}</color>, ", type.ToLowerInvariant());
sb.Remove(sb.Length - 2, 2);
sb.AppendLine();
user.SendChatMessage(sb);
}
19
Source : Util.cs
with MIT License
from chucklenugget
with MIT License
from chucklenugget
public static bool TryParseEnum<T>(string str, out T value) where T : struct
{
if (!typeof(T).IsEnum)
throw new ArgumentException("Type parameter must be an enum");
foreach (var name in Enum.GetNames(typeof(T)))
{
if (String.Equals(name, str, StringComparison.OrdinalIgnoreCase))
{
value = (T)Enum.Parse(typeof(T), name);
return true;
}
}
value = default(T);
return false;
}
19
Source : SteamVR_Input_Source.cs
with GNU General Public License v3.0
from CircuitLord
with GNU General Public License v3.0
from CircuitLord
public static void Initialize()
{
List<SteamVR_Input_Sources> allSourcesList = new List<SteamVR_Input_Sources>();
string[] enumNames = System.Enum.GetNames(enumType);
inputSourceHandlesBySource = new ulong[enumNames.Length];
inputSourceSourcesByHandle = new Dictionary<ulong, SteamVR_Input_Sources>();
for (int enumIndex = 0; enumIndex < enumNames.Length; enumIndex++)
{
string path = GetPath(enumNames[enumIndex]);
ulong handle = 0;
EVRInputError err = OpenVR.Input.GetInputSourceHandle(path, ref handle);
if (err != EVRInputError.None)
Debug.LogError("<b>[SteamVR]</b> GetInputSourceHandle (" + path + ") error: " + err.ToString());
if (enumNames[enumIndex] == SteamVR_Input_Sources.Any.ToString()) //todo: temporary hack
{
inputSourceHandlesBySource[enumIndex] = 0;
inputSourceSourcesByHandle.Add(0, (SteamVR_Input_Sources)enumIndex);
}
else
{
inputSourceHandlesBySource[enumIndex] = handle;
inputSourceSourcesByHandle.Add(handle, (SteamVR_Input_Sources)enumIndex);
}
allSourcesList.Add((SteamVR_Input_Sources)enumIndex);
}
allSources = allSourcesList.ToArray();
}
19
Source : ReflectionHelper.cs
with MIT License
from CitiesSkylinesMultiplayer
with MIT License
from CitiesSkylinesMultiplayer
public static int GetEnumValue(Type enumType, string value)
{
int i = 0;
foreach (string name in Enum.GetNames(enumType))
{
if (name.Equals(value))
{
return (int)Enum.GetValues(enumType).GetValue(i);
}
i++;
}
return 0;
}
19
Source : PromptCommandAttribute.cs
with MIT License
from CityOfZion
with MIT License
from CityOfZion
private object ParseToArgument(CommandToken token, Type type)
{
// Custom converters
if (_customConvertes.TryGetValue(type, out var converter))
{
return converter(token);
}
// Array
if (type.IsArray)
{
var l = new List<object>();
var gt = type.GetElementType();
foreach (var ii in token.Value.Split(_splitChars))
{
var ov = ParseToArgument(new CommandToken(ii, false), gt);
if (ov == null) continue;
l.Add(ov);
}
var a = (Array)Activator.CreateInstance(type, l.Count);
Array.Copy(l.ToArray(), a, l.Count);
return a;
}
// List
if (_iListType.IsreplacedignableFrom(type))
{
var l = (IList)Activator.CreateInstance(type);
// If dosen't have T return null
if (type.GenericTypeArguments == null || type.GenericTypeArguments.Length == 0)
return null;
var gt = type.GenericTypeArguments[0];
foreach (var ii in token.Value.Split(_splitChars))
{
var ov = ParseToArgument(new CommandToken(ii, false), gt);
if (ov == null) continue;
l.Add(ov);
}
return l;
}
if (type.IsEnum)
{
var iret = 0L;
var f = Enum.GetNames(type);
foreach (var en in token.Value.Split(new char[] { ',', '|' }, StringSplitOptions.RemoveEmptyEntries))
{
foreach (var v in f)
{
if (string.Compare(v, en, true) == 0)
{
var v1 = Enum.Parse(type, v);
if (v1 != null)
{
if (iret == 0L)
{
iret = Convert.ToInt64(v1);
}
else
{
// Multienum One|Two
iret |= Convert.ToInt64(v1);
}
}
}
}
}
return Enum.ToObject(type, iret);
}
// Is Convertible
var conv = System.ComponentModel.TypeDescriptor.GetConverter(type);
if (conv.CanConvertFrom(_stringType))
{
return conv.ConvertFrom(token.Value);
}
throw (new InvalidParameterException());
}
19
Source : AutoCommandComplete.cs
with MIT License
from CityOfZion
with MIT License
from CityOfZion
private IEnumerable<string> EnumValues(Type type)
{
foreach (var name in Enum.GetNames(type))
{
yield return name;
}
}
19
Source : AxisMapping.cs
with GNU General Public License v3.0
from Cleric-K
with GNU General Public License v3.0
from Cleric-K
private void initializePanel()
{
panel = new FlowLayoutPanel();
panel.SuspendLayout();
panel.Size = new Size(600, 30);
var label = new Label();
label.Text = "Channel:";
label.Size = new Size(52, 20);
label.TextAlign = ContentAlignment.MiddleLeft;
panel.Controls.Add(label);
channelSpinner = new NumericUpDown();
channelSpinner.Minimum = 0;
channelSpinner.Maximum = 255;
channelSpinner.Size = new Size(42, 20);
channelSpinner.Value = Channel+1;
channelSpinner.ValueChanged += onChannelChange;
panel.Controls.Add(channelSpinner);
label = new Label();
label.Text = "Axis:";
label.Size = new Size(42, 20);
label.TextAlign = ContentAlignment.MiddleLeft;
panel.Controls.Add(label);
joystickAxisDropdown = new ComboBox();
joystickAxisDropdown.DropDownStyle = ComboBoxStyle.DropDownList;
joystickAxisDropdown.Size = new Size(42, 20);
joystickAxisDropdown.Items.AddRange(Enum.GetNames(typeof(VJoyBase.Axes)));
joystickAxisDropdown.SelectedIndex = Axis;
joystickAxisDropdown.SelectedIndexChanged += onAxisChange;
panel.Controls.Add(joystickAxisDropdown);
label = new Label();
label.Text = "Input:";
label.Size = new Size(42, 20);
label.TextAlign = ContentAlignment.MiddleLeft;
panel.Controls.Add(label);
inputLabel = new Label();
inputLabel.Text = "-";
inputLabel.Size = new Size(42, 20);
inputLabel.TextAlign = ContentAlignment.MiddleLeft;
panel.Controls.Add(inputLabel);
label = new Label();
label.Text = "Output:";
label.Size = new Size(42, 20);
label.TextAlign = ContentAlignment.MiddleLeft;
panel.Controls.Add(label);
progressBox = new PictureBox();
progressBox.Size = new Size(80, 20);
progressBox.BorderStyle = BorderStyle.FixedSingle;
progressBox.Paint += onProgressPaint;
panel.Controls.Add(progressBox);
var button = new Button();
button.Text = "Setup";
button.Click += onSetupClick;
button.Size = new Size(50, 20);
panel.Controls.Add(button);
button = new Button();
button.Text = "Remove";
button.Click += onRemoveClick;
button.Size = new Size(55, 20);
panel.Controls.Add(button);
panel.ResumeLayout();
}
19
Source : EnumHelper.cs
with MIT License
from cloudnative-netcore
with MIT License
from cloudnative-netcore
public static (IEnumerable<TKey>, IEnumerable<string>) GetMetadata<TEnum, TKey>()
{
var keyArray = (TKey[])Enum.GetValues(typeof(TEnum));
var nameArray = Enum.GetNames(typeof(TEnum));
IList<TKey> keys = new List<TKey>();
foreach (var item in keyArray) keys.Add(item);
IList<string> names = new List<string>();
foreach (var item in nameArray) names.Add(item);
return (keys, names);
}
19
Source : BuiltInCommands.cs
with MIT License
from Cobo3
with MIT License
from Cobo3
[Command]
static string GetEnumValues(string enumName)
{
string text = string.Empty;
Type[] types = ReflectionFinder.enumTypes;
//When the same enum name is defined in multiple namespaces, then more than one match can be found
List<Type> matches = new List<Type>();
for (int i = 0; i < types.Length; i++)
if (types[i].Name.Equals(enumName, StringComparison.OrdinalIgnoreCase))
matches.Add(types[i]);
//TODO This should be done inside the previous loop
for (int i = 0; i < matches.Count; i++)
{
string[] values = Enum.GetNames(matches[i]);
text += matches[i].FullName.Replace('+', '.') + ":\n";
for (int j = 0; j < values.Length; j++)
text += "\t" + values[j] + "\n";
}
return text;
}
19
Source : EnumUtil.cs
with MIT License
from cocosip
with MIT License
from cocosip
public static int GetEnumLength<T>()
{
return Enum.GetNames(typeof(T)).Length;
}
19
Source : Utils.cs
with MIT License
from coding2233
with MIT License
from coding2233
public static void RegisterEnumType(RealStatePtr L, Type type)
{
ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);
foreach (var name in Enum.GetNames(type))
{
RegisterObject(L, translator, Utils.CLS_IDX, name, Enum.Parse(type, name));
}
}
19
Source : Base_SysLogController.cs
with Apache License 2.0
from Coldairarrow
with Apache License 2.0
from Coldairarrow
public ActionResult GetLogTypeList()
{
List<object> logTypeList = new List<object>();
Enum.GetNames(typeof(EnumType.LogType)).ForEach(aName =>
{
logTypeList.Add(new { Name = aName, Value = aName });
});
return Content(logTypeList.ToJson());
}
19
Source : Base_SysLogController.cs
with MIT License
from Coldairarrow
with MIT License
from Coldairarrow
public ActionResult GetLogTypeList()
{
List<object> logTypeList = new List<object>();
Enum.GetNames(typeof(LogType)).ForEach(aName =>
{
logTypeList.Add(new { Name = aName, Value = aName });
});
return Content(logTypeList.ToJson());
}
19
Source : Specification.cs
with MIT License
from commandlineparser
with MIT License
from commandlineparser
public static Specification FromProperty(PropertyInfo property)
{
var attrs = property.GetCustomAttributes(true);
var oa = attrs.OfType<OptionAttribute>();
if (oa.Count() == 1)
{
var spec = OptionSpecification.FromAttribute(oa.Single(), property.PropertyType,
ReflectionHelper.GetNamesOfEnum(property.PropertyType));
if (spec.ShortName.Length == 0 && spec.LongName.Length == 0)
{
return spec.WithLongName(property.Name.ToLowerInvariant());
}
return spec;
}
var va = attrs.OfType<ValueAttribute>();
if (va.Count() == 1)
{
return ValueSpecification.FromAttribute(va.Single(), property.PropertyType,
property.PropertyType.GetTypeInfo().IsEnum
? Enum.GetNames(property.PropertyType)
: Enumerable.Empty<string>());
}
throw new InvalidOperationException();
}
19
Source : ReflectionHelper.cs
with MIT License
from commandlineparser
with MIT License
from commandlineparser
public static IEnumerable<string> GetNamesOfEnum(Type t)
{
if (t.IsEnum)
return Enum.GetNames(t);
Type u = Nullable.GetUnderlyingType(t);
if (u != null && u.IsEnum)
return Enum.GetNames(u);
return Enumerable.Empty<string>();
}
19
Source : Extensions.cs
with Apache License 2.0
from commercetools
with Apache License 2.0
from commercetools
public static object GetEnum(this string value, Type enumType)
{
var typeofEnum = enumType;
if (!enumType.IsEnum && enumType.IsGenericType)
{
typeofEnum = Nullable.GetUnderlyingType(enumType);
}
if (typeofEnum != null && typeofEnum.IsEnum)
{
string[] names = Enum.GetNames(typeofEnum);
foreach (string name in names)
{
if (GetDescription((Enum) Enum.Parse(typeofEnum, name)).Equals(value))
{
return Enum.Parse(typeofEnum, name);
}
}
}
throw new ArgumentException();
}
19
Source : Extensions.cs
with Apache License 2.0
from commercetools
with Apache License 2.0
from commercetools
public static T GetEnum<T>(this string value) where T : Enum
{
string[] names = Enum.GetNames(typeof(T));
foreach (string name in names)
{
if (GetDescription((Enum)Enum.Parse(typeof(T), name)).Equals(value))
{
return (T)Enum.Parse(typeof(T), name);
}
}
throw new ArgumentException();
}
19
Source : SchemaBuilder.cs
with MIT License
from Cooke
with MIT License
from Cooke
private BaseType CreateType(Type clrType, bool withinInputType = false)
{
clrType = TypeHelper.UnwrapTask(clrType);
var typeCacheKey = new TypeCacheKey { ClrType = clrType, IsInput = withinInputType && !TypeHelper.IsList(clrType) && clrType.GetTypeInfo().IsClreplaced };
if (_types.ContainsKey(typeCacheKey))
{
return _types[typeCacheKey];
}
if (clrType == typeof(bool))
{
_types[typeCacheKey] = BooleanType.Instance;
return StringType.Instance;
}
if (clrType == typeof(string))
{
_types[typeCacheKey] = StringType.Instance;
return StringType.Instance;
}
if (clrType == typeof(int))
{
_types[typeCacheKey] = IntType.Instance;
return IntType.Instance;
}
if (clrType.GetTypeInfo().IsEnum)
{
var enumType = new EnumType(Enum.GetNames(clrType).Select(x => new EnumValue(x)), clrType);
_types[typeCacheKey] = enumType;
return enumType;
}
if (TypeHelper.IsList(clrType))
{
var listEnumerableType = clrType.GetTypeInfo().ImplementedInterfaces.Concat(new[] { clrType })
.First(x => x.IsConstructedGenericType && x.GetGenericTypeDefinition() == typeof(IEnumerable<>));
var listGraphType = new ListType();
_types[typeCacheKey] = listGraphType;
listGraphType.ItemType = CreateType(listEnumerableType.GenericTypeArguments.Single(), withinInputType);
return listGraphType;
}
if (clrType.GetTypeInfo().IsClreplaced)
{
var baseType = clrType.GetTypeInfo().BaseType;
BaseType baseGraphType = null;
if (baseType != typeof(object))
{
baseGraphType = CreateType(baseType, withinInputType);
}
if (!withinInputType)
{
BaseType resultGraphType;
if (clrType.GetTypeInfo().IsAbstract)
{
var interfaceGraphType = new InterfaceType(clrType);
_types[typeCacheKey] = interfaceGraphType;
interfaceGraphType.Fields = CreateFields(clrType);
resultGraphType = interfaceGraphType;
}
else
{
var objectGraphType = new ObjectType(clrType);
_types[typeCacheKey] = objectGraphType;
objectGraphType.Fields = CreateFields(clrType);
// TODO better support for interface types
objectGraphType.Interfaces = baseGraphType?.Kind == __TypeKind.Interface
? new List<InterfaceType> {(InterfaceType) baseGraphType}.ToArray()
: new InterfaceType[0];
resultGraphType = objectGraphType;
}
foreach (var subType in clrType.GetTypeInfo().replacedembly.DefinedTypes.Where(x => x.BaseType == clrType))
{
CreateType(subType.AsType());
}
return resultGraphType;
}
else
{
var inputObjectGraphType = new InputObjectType(clrType);
_types[typeCacheKey] = inputObjectGraphType;
inputObjectGraphType.Fields = CreateInputFields(clrType);
return inputObjectGraphType;
}
}
throw new NotSupportedException($"The given CLR type '{clrType}' is currently not supported.");
}
19
Source : EnumField.cs
with MIT License
from cr4yz
with MIT License
from cr4yz
protected override void OnBound( MemberInfo variable )
{
base.OnBound( variable );
if( !enumNames.TryGetValue( BoundVariableType, out currEnumNames ) || !enumValues.TryGetValue( BoundVariableType, out currEnumValues ) )
{
string[] names = Enum.GetNames( BoundVariableType );
Array values = Enum.GetValues( BoundVariableType );
currEnumNames = new List<string>( names.Length );
currEnumValues = new List<object>( names.Length );
for( int i = 0; i < names.Length; i++ )
{
currEnumNames.Add( names[i] );
currEnumValues.Add( values.GetValue( i ) );
}
enumNames[BoundVariableType] = currEnumNames;
enumValues[BoundVariableType] = currEnumValues;
}
input.ClearOptions();
input.AddOptions( currEnumNames );
}
19
Source : GridObjectLayoutControl.cs
with MIT License
from cre8ivepark
with MIT License
from cre8ivepark
public void NextLayout()
{
LayoutAnchor currentLayout = grid.Anchor;
var anchorTypeCount = Enum.GetNames(typeof(LayoutAnchor)).Length;
int nextLayout = (((int)currentLayout) + 1) % anchorTypeCount;
grid.Anchor = (LayoutAnchor)nextLayout;
UpdateUI();
}
See More Examples