public bool InteractUI(EntityUid uid, Enum?key, IntrinsicUIComponent?iui = null, ActorComponent?actor = null) { if (!Resolve(uid, ref iui, ref actor)) { return(false); } if (key is null) { Logger.ErrorS("bui", $"Entity {ToPrettyString(uid)} has an invalid intrinsic UI."); } var ui = GetUIOrNull(uid, key, iui); if (ui is null) { Logger.ErrorS("bui", $"Couldn't get UI {key} on {ToPrettyString(uid)}"); return(false); } var attempt = new IntrinsicUIOpenAttemptEvent(uid, key); RaiseLocalEvent(uid, attempt, false); if (attempt.Cancelled) { return(false); } ui.Toggle(actor.PlayerSession); return(true); }
public override void AddCommandParameter( DbCommand cmd, string paramName, object?paramValue, Enum?dataType = null, int?size = null) { // deeded for SQL Server CE if (paramValue is bool && dataType == null) { paramValue = (bool)paramValue ? 1 : 0; } // varbinary support if (size == null && dataType != null && dataType.Equals(DbProvider.Metadata.DbBinaryType)) { size = -1; } // avoid size inferred from value that cause multiple query plans if (size == null && paramValue is string) { size = 4000; } base.AddCommandParameter(cmd, paramName, paramValue, dataType, size); }
/// <inheritdoc /> public bool TryParseEnumReference(string reference, [NotNullWhen(true)] out Enum? @enum) { if (!reference.StartsWith("enum.")) { @enum = default; return(false); } reference = reference.Substring(5); var dotIndex = reference.LastIndexOf('.'); var typeName = reference.Substring(0, dotIndex); var value = reference.Substring(dotIndex + 1); foreach (var assembly in assemblies) { foreach (var type in assembly.DefinedTypes) { if (!type.IsEnum || !type.FullName !.EndsWith(typeName)) { continue; } @enum = (Enum)Enum.Parse(type, value); return(true); } } throw new ArgumentException("Could not resolve enum reference."); }
public void AddCommandParameter( IDbCommand cmd, string paramName, object?paramValue, Enum?dataType, int?size) { IDbDataParameter param = cmd.CreateParameter(); if (dataType != null) { SetDataTypeToCommandParameter(param, dataType); } if (size != null) { param.Size = size.Value; } param.ParameterName = dbProvider.Metadata.GetParameterName(paramName); param.Value = paramValue ?? DBNull.Value; cmd.Parameters.Add(param); if (!dbProvider.Metadata.BindByName) { cmd.CommandText = cmd.CommandText.Replace("@" + paramName, dbProvider.Metadata.ParameterNamePrefix); } else if (dbProvider.Metadata.ParameterNamePrefix != "@") { // we need to replace cmd.CommandText = cmd.CommandText.Replace("@" + paramName, dbProvider.Metadata.ParameterNamePrefix + paramName); } }
public int Compare(Enum?x, Enum?y) { if (x is null && y is null) { return(0); } if (x is null && y is not null) { return(-1); } if (x is not null && y is null) { return(1); } if (_useName) { string left = x?.ToString() ?? string.Empty; string right = y?.ToString() ?? string.Empty; return(left == right ? 0 : 1); } else { long left = Convert.ToInt64(x); long right = Convert.ToInt64(y); return(left == right ? 0 : left < right ? -1 : 1); } }
private static WebApiErrorResponse CreateBadRequestResponse(string?errorMessage, Enum?errorCodeType, Enum?errorCode, IEnumerable <WebApiErrorBase>?errors) { //create and initialize new error response var response = new WebApiErrorResponse { //bad request is default status code HttpStatusCode = HTTP_BAD_REQUEST_ERROR_CODE, //this is an error, set is error to true IsError = true, //set our error message Message = errorMessage, //set error code information ErrorCodeType = errorCodeType != null?Convert.ToInt32(errorCodeType) : null, ErrorCodeTypeReadable = errorCodeType?.ToString(), ErrorCode = errorCode != null?Convert.ToInt32(errorCode) : null, ErrorCodeReadable = errorCode?.ToString(), //add any optional extended errors Errors = errors ! }; //return response return(response); } #endregion }
public JsonStringEnumMemberConverterHelper(JsonNamingPolicy?namingPolicy, bool allowIntegerValues) { _AllowIntegerValues = allowIntegerValues; _EnumType = typeof(TEnum); _EnumTypeCode = Type.GetTypeCode(_EnumType); _IsFlags = _EnumType.IsDefined(typeof(FlagsAttribute), true); string[] builtInNames = _EnumType.GetEnumNames(); Array builtInValues = _EnumType.GetEnumValues(); _RawToTransformed = new Dictionary <TEnum, EnumInfo>(); _TransformedToRaw = new Dictionary <string, EnumInfo>(); for (int i = 0; i < builtInNames.Length; i++) { Enum?enumValue = (Enum?)builtInValues.GetValue(i); if (enumValue == null) { continue; } ulong rawValue = GetEnumValue(enumValue); string name = builtInNames[i]; FieldInfo field = _EnumType.GetField(name, EnumBindings) !; EnumMemberAttribute?enumMemberAttribute = field.GetCustomAttribute <EnumMemberAttribute>(true); string transformedName = enumMemberAttribute?.Value ?? namingPolicy?.ConvertName(name) ?? name; //if (enumValue is not TEnum typedValue) // throw new NotSupportedException(); var typedValue = (TEnum)enumValue; _RawToTransformed[typedValue] = new EnumInfo(transformedName, typedValue, rawValue); _TransformedToRaw[transformedName] = new EnumInfo(name, typedValue, rawValue); } }
private BoundUserInterface?GetUIOrNull(EntityUid uid, Enum?key, IntrinsicUIComponent?component = null) { if (!Resolve(uid, ref component)) { return(null); } return(key is null ? null : uid.GetUIOrNull(key)); }
public Utility_SerializableTypeModeViewModel(Enum?gameMode, string?displayName = null, Games?game = null) { GameModeBaseAttribute?attr = gameMode?.GetAttribute <GameModeBaseAttribute>(); GameMode = gameMode; DisplayName = displayName ?? attr?.DisplayName ?? "NULL"; Game = game ?? attr?.Game; GetDefaultDir = () => Game?.GetInstallDir(false); }
public TemperatureSourceData(Enum?source, ushort register, ushort halfRegister = 0, int halfBit = -1, ushort sourceRegister = 0, ushort?alternateRegister = null) { Source = source; Register = register; HalfRegister = halfRegister; HalfBit = halfBit; SourceRegister = sourceRegister; AlternateRegister = alternateRegister; }
public static string?Describe(this Enum?e, bool titalize = false) { var lower = e?.ToString().ToLowerInvariant(); if (titalize) { return(lower?.Titalize()); } return(lower); }
/// <inheritdoc /> public virtual Enum?GetEnum(Type enumType, string path, Enum? @default = null) { if (enumType == null) { throw new ArgumentException(nameof(enumType)); } var value = GetNode(path); return(value != null?value.GetEnum(enumType) : @default); }
void ISerializationHooks.AfterDeserialization() { var reflectionManager = IoCManager.Resolve <IReflectionManager>(); if (reflectionManager.TryParseEnumReference(_keyRaw, out var key)) { Key = key; } else { Logger.Error($"Invalid UI key ({_keyRaw}) in open-UI action"); } }
/// <summary> /// Parse a unit by the unit enum type <paramref name="unitType" /> and a unit enum value <paramref name="unitName" />> /// </summary> /// <param name="unitType">Unit type, such as <see cref="LengthUnit" />.</param> /// <param name="unitName">Unit name, such as "Meter" corresponding to <see cref="LengthUnit.Meter" />.</param> /// <param name="unitValue">The return enum value, such as <see cref="LengthUnit.Meter" /> boxed as an object.</param> /// <returns>True if succeeded, otherwise false.</returns> /// <exception cref="UnitNotFoundException">No unit values match the <paramref name="unitName" />.</exception> private static bool TryParseUnit(Type unitType, string unitName, out Enum?unitValue) { unitValue = null; var eNames = Enum.GetNames(unitType); unitName = eNames.FirstOrDefault(x => x.Equals(unitName.Trim(), StringComparison.OrdinalIgnoreCase)); if (unitName == null) { return(false); } unitValue = (Enum)Enum.Parse(unitType, unitName); return(true); }
private static Enum DrawSingleProperty(Type type, Enum?dependantOn) { //returns a random value from the enum's range //TODO: maybe a random list element? XD //src of this crap: https://stackoverflow.com/a/27744237/12938809 var values = Enum.GetValues(type).Cast <Enum>().ToList(); //the intersection of Enum's values with the affected properties gives us a neat range var range = dependantOn != null ? _affectedProperties[dependantOn].Intersect(values).ToArray(): values.ToArray(); //pick a random number r from 0 to range.Length, take the item on index r, cast to enum, return var value = (Enum)range.GetValue(_random.Next(range.Length)); return(value); }
public SubModel( DateTime dateTimeProp = new DateTime(), Enum?enumProp = null, Guid?guidProp = null, int?intProp = null, string stringProp = null, IEnumerable <int> arrayProp = null) { this.DateTimeProp = dateTimeProp; this.EnumProp = enumProp; this.GuidProp = guidProp; this.IntProp = intProp; this.StringProp = stringProp; this.ArrayProp = arrayProp; }
/// <summary> /// Initializes this instance. Parses information and initializes startup /// values. /// </summary> public void Init() { // parse value to db binary column type if (dbBinaryTypeName != null) { // not inited yet if (ParameterDbType == null || ParameterType == null) { throw new ArgumentException($"Couldn't parse parameter db type for database type '{ProductName}'"); } dbBinaryType = (Enum)Enum.Parse(ParameterDbType, dbBinaryTypeName); ParameterDbTypeProperty = ParameterType.GetProperty(parameterDbTypePropertyName) !; if (ParameterDbTypeProperty == null) { throw new ArgumentException($"Couldn't parse parameter db type for database type '{ProductName}'"); } } }
public bool TryConvert(ConverterContext ctx, Arg arg, out Enum?value) { value = null; var targetType = ctx.TargetType; if (!targetType.IsEnum) { return(false); } // Try to find enum value by attribute, name, or value var enumValue = ResolveEnum(ctx.ParseOptions, targetType, arg.Value) as Enum; if (enumValue == null) { throw new InvalidCastException($"Given value \"{value}\" cannot be converted to enum type \"{targetType.FullName}\""); } return(true); }
public JsonStringEnumMemberConverter(JsonNamingPolicy?namingPolicy, bool allowIntegerValues, Type?underlyingType) { Debug.Assert( (typeof(T).IsEnum && underlyingType == null) || (Nullable.GetUnderlyingType(typeof(T)) == underlyingType), "Generic type is invalid."); _AllowIntegerValues = allowIntegerValues; _UnderlyingType = underlyingType; _EnumType = _UnderlyingType ?? typeof(T); _EnumTypeCode = Type.GetTypeCode(_EnumType); _IsFlags = _EnumType.IsDefined(typeof(FlagsAttribute), true); string[] builtInNames = _EnumType.GetEnumNames(); Array builtInValues = _EnumType.GetEnumValues(); _RawToTransformed = new Dictionary <ulong, EnumInfo>(); _TransformedToRaw = new Dictionary <string, EnumInfo>(); for (int i = 0; i < builtInNames.Length; i++) { Enum?enumValue = (Enum?)builtInValues.GetValue(i); if (enumValue == null) { continue; } ulong rawValue = GetEnumValue(enumValue); string name = builtInNames[i]; FieldInfo field = _EnumType.GetField(name, EnumBindings) !; EnumMemberAttribute?enumMemberAttribute = field.GetCustomAttribute <EnumMemberAttribute>(true); string transformedName = enumMemberAttribute?.Value ?? namingPolicy?.ConvertName(name) ?? name; _RawToTransformed[rawValue] = new EnumInfo(transformedName, enumValue, rawValue); _TransformedToRaw[transformedName] = new EnumInfo(name, enumValue, rawValue); } }
public static string?GetDisplayName(this Enum?enumeration, bool returnDefault = true) => enumeration == null ? null : enumeration.GetAttribute <DisplayNameAttribute>()?.DisplayName ?? enumeration.GetAttribute <DisplayAttribute>()?.Name ?? (returnDefault ? enumeration.ToString() : string.Empty);
/// <summary> /// Initializes a new instance of the <see cref="ValidationResult"/> class. /// </summary> /// <param name="validationRule">The validation rule.</param> /// <param name="details">The details.</param> public ValidationResult(Enum validationRule, IEnumerable <ValidationResult> details) { this._validationRule = validationRule; this.resultDetails = new List <ValidationResult>(details); }
//Kunne man have A og b her? public BaseUnitClass(Enum?baseUnitType) { Count = 0; BaseUnitType = baseUnitType; }
/// <summary> /// Initializes a new instance of the <see cref="UnitAttributeBase"/> class. /// </summary> /// <param name="unitType"></param> public UnitAttributeBase(object unitType) { UnitType = unitType as Enum; }
public IntrinsicUIOpenAttemptEvent(EntityUid who, Enum?key) { User = who; Key = key; }
public static void ThisDoesNotWork() { Enum?e = Enum.One; DoSomething("abc", Enum.Two, ref e); }
/// <summary> /// Gets an attribute on an enum field value /// </summary> /// <typeparam name="T">The type of the attribute you want to retrieve</typeparam> /// <param name="enumVal">The enum value</param> /// <returns>The attribute of type T that exists on the enum value</returns> /// <example>string desc = myEnumVariable.GetAttributeOfType<DescriptionAttribute>().Description;</DescriptionAttribute>></example> public static T?GetAttribute <T>(this Enum?enumVal) where T : Attribute { if (enumVal == null) { return(default);
public static string?GetEnumMember(this Enum?enumeration, bool returnDefault = true) => enumeration == null ? null : enumeration.GetAttribute <EnumMemberAttribute>()?.Value ?? (returnDefault ? enumeration.ToString() : string.Empty);
public bool TryParse(string?unitAbbreviation, Type unitType, IFormatProvider?formatProvider, out Enum?unit) { if (unitAbbreviation == null) { unit = default; return(false); } unitAbbreviation = unitAbbreviation.Trim(); unit = default; if (!_unitAbbreviationsCache.TryGetUnitValueAbbreviationLookup(unitType, formatProvider, out var abbreviations)) { return(false); } var unitIntValues = abbreviations !.GetUnitsForAbbreviation(unitAbbreviation, ignoreCase: true); if (unitIntValues.Count == 0) { unitAbbreviation = NormalizeUnitString(unitAbbreviation); unitIntValues = abbreviations.GetUnitsForAbbreviation(unitAbbreviation, ignoreCase: true); } // Narrow the search if too many hits, for example Megabar "Mbar" and Millibar "mbar" need to be distinguished if (unitIntValues.Count > 1) { unitIntValues = abbreviations.GetUnitsForAbbreviation(unitAbbreviation, ignoreCase: false); } if (unitIntValues.Count != 1) { return(false); } unit = (Enum)Enum.ToObject(unitType, unitIntValues[0]); return(true); }
public bool TryParse(string unitAbbreviation, Type unitType, out Enum?unit) { return(TryParse(unitAbbreviation, unitType, null, out unit)); }
/// <summary> /// Opens Inara in a webdriver browser and searches for the specified T criteria. Will automatically put in the fields to search for and the last known system the player exited supercruise at /// </summary> /// <typeparam name="T">The enum that you are searching for</typeparam> /// <param name="vaProxy">VoiceAttackProxy object</param> /// <param name="url">The url that you want the webdriver to open</param> /// <param name="vaVarName">The voice attack variable that you want to be parsed to match T</param> /// <param name="lastKnownSystem">The last known system that the player exited supercruise at if available(Defaults to Sol)</param> public bool OpenInara <T>(VoiceAttackProxy vaProxy, string url, string vaVarName, string lastKnownSystem) where T : Enum { Enum?_addUrlEnd = null; if (typeof(T) != typeof(MaterialTraderTypes.MaterialTraderType)) { _addUrlEnd = EnumParser.ParseStringToEnum <T>(vaProxy, vaVarName, typeof(T)); if (_addUrlEnd == null) { vaProxy.WriteToLog($"An error occurred. Parsed value is null", LogColors.LogColor.red); return(false); } } try { /*Current workaround if the user closes the spawned webdriver or web browser window. This slows down the application as it has to wait on a time out exception * to be throw in order to set the driver to null therefore allowing the GetDriver method to return a new ChromeDriver. This is the only way I can currently enforce * driver to be a singleton in order to prevent the plugin from opening multiple chrome windows each time that a command is ran. */ if (isBrowserClosed()) { Driver = null; } Driver = GetDriver(); #region Set url based on search context try { if (typeof(T) == typeof(Ships.Ship)) { var shipUrlPost = Constants.ShipSearchPreFix + Convert.ToInt32(_addUrlEnd); Driver.Url = url + shipUrlPost; } else if (typeof(T) == typeof(MaterialTraderTypes.MaterialTraderType)) { Driver.Url = url; } else { Driver.Url = url + Convert.ToInt32(_addUrlEnd); } } catch (Exception) { vaProxy.WriteToLog($"ERROR: Could not connect to the webdriver, Check your network connection and try again", LogColors.LogColor.red); return(false); } #endregion #region Module and Ship Search //Searches based on the Module and Ship search context if (typeof(T) == typeof(Modules.Module) || typeof(T) == typeof(Ships.Ship)) { try { var name = Driver.FindElement(By.CssSelector(Constants.ModuleNameCssSelector)); var module_name = name.Text; var input = Driver.FindElement(By.CssSelector(Constants.ModuleShipInputCssSelector)); input.SendKeys(module_name); Thread.Sleep(500); if (typeof(T) == typeof(Ships.Ship)) { input.SendKeys(Keys.Enter); } if (typeof(T) == typeof(Modules.Module)) { var webElements = Driver.FindElements(By.TagName("li")); foreach (var element in webElements) { if (element.Text.ToLower() == module_name.ToLower()) { element.Click(); } } } var near = Driver.FindElement(By.XPath(Constants.ModuleShipNearestSystemInputXPath)); near.Clear(); near.SendKeys(lastKnownSystem); near.SendKeys(Keys.Enter); var submit = Driver.FindElement(By.CssSelector(Constants.ModuleShipSubmitButtonCssSelector)); submit.Click(); } catch (Exception e) { vaProxy.WriteToLog($"An error occurred looking up the module", LogColors.LogColor.red); vaProxy.WriteToLog($"{e.StackTrace}", LogColors.LogColor.pink); vaProxy.WriteToLog($"{e.Message}", LogColors.LogColor.pink); return(false); } } #endregion #region Commodity Search //Commodity search specific code if (typeof(T) == typeof(Commodities.Commodity)) { var starSystemSearch = Driver.FindElement(By.XPath(Constants.CommodityStarSystemSearchXPath)); starSystemSearch.SendKeys(lastKnownSystem); starSystemSearch.SendKeys(Keys.Enter); if (vaProxy.GetText("buyorsell") == "buy") { var exports = Driver.FindElement(By.XPath(Constants.CommodityExportsButtonXPath)); exports.Click(); } } #endregion if (typeof(T) == typeof(MaterialTraderTypes.MaterialTraderType)) { var matTraderCheckBox = Driver.FindElement(By.XPath("//*[@id=\"galaxysearchstations\"]/div/form/div[3]/div[6]/div/label")); matTraderCheckBox.Click(); var systemSearchBox = Driver.FindElement(By.Id("autocompletestar")); systemSearchBox.Clear(); systemSearchBox.SendKeys(lastKnownSystem); Thread.Sleep(1000); systemSearchBox.SendKeys(Keys.Enter); var table = Driver.FindElement(By.XPath("//*[@id=\"DataTables_Table_0\"]/tbody")); var results = table.FindElements(By.TagName("tr")); IWebElement match = null; IWebElement clipBoard = null; int lightSeconds = 0; string stationName = string.Empty; string starSystem = string.Empty; foreach (var result in results) { var data = result.FindElements(By.TagName("td")); foreach (var item in data) { if (item.Text.Contains("Ls")) { lightSeconds = int.Parse(item.Text.Replace("Ls", "").Replace(" ", "").Replace(",", "")); } if (item.Text.ToLowerInvariant() == vaProxy.GetText(Constants.VoiceAttackMaterialTraderTypeVariable).ToLowerInvariant() && (lightSeconds <= 5000)) { match = result; goto Loopend; } } } Loopend: if (match == null) { return(false); } var matchData = match.FindElements(By.TagName("td")); var lineRight = match.FindElements(By.ClassName("lineright")); var pattern = @"(starsystem)"; foreach (var item in matchData) { var links = item.FindElements(By.TagName("a")); foreach (var link in links) { if (Regex.Match(link.GetAttribute("href"), pattern, RegexOptions.IgnoreCase).Success) { starSystem = link.Text; break; } } foreach (var i in lineRight) { var childen = i.FindElements(By.CssSelector("*")); foreach (var c in childen) { if (c.GetAttribute("class").Contains("toclipboard")) { clipBoard = c; goto FoundClipboard; } } } FoundClipboard: if (item.GetAttribute("class").Contains("wrap")) { stationName = item.FindElement(By.ClassName("inverse")).Text; } } if (clipBoard != null) { clipBoard.Click(); } vaProxy.SetText(Constants.VoiceAttackMaterialTraderStation, stationName); vaProxy.SetText(Constants.VoiceAttackMaterialStarSystem, starSystem); } vaProxy.SetBoolean(Constants.VoiceAttackWebDriverSuccessVariable, true); return(true); } catch (Exception e) { DisplayWebDriverError(vaProxy, e); return(false); } }