System.Enum.Parse(System.Type, string, bool)

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

2242 Examples 7

19 View Source File : ExpressionResolver.cs
License : MIT License
Project Creator : 17MKH

private static void ResolveInForGeneric(StringBuilder sqlBuilder, string columnName, Expression exp, Type valueType, bool notContainer = false)
    {
        var value = ResolveDynamicInvoke(exp);
        var isValueType = false;
        var list = new List<string>();
        if (valueType.IsEnum)
        {
            isValueType = true;
            var valueList = (IEnumerable)value;
            if (valueList != null)
            {
                foreach (var c in valueList)
                {
                    list.Add(Enum.Parse(valueType, c.ToString()!).ToInt().ToString());
                }
            }
        }
        else
        {
            var typeName = valueType.Name;
            switch (typeName)
            {
                case "Guid":
                    if (value is IEnumerable<Guid> guidValues)
                    {
                        foreach (var c in guidValues)
                        {
                            list.Add(c.ToString());
                        }
                    }
                    break;
                case "DateTime":
                    if (value is IEnumerable<DateTime> dateTimeValues)
                    {
                        foreach (var c in dateTimeValues)
                        {
                            list.Add(c.ToString("yyyy-MM-dd HH:mm:ss"));
                        }
                    }
                    break;
                case "Byte":
                    isValueType = true;
                    if (value is IEnumerable<byte> byteValues)
                    {
                        foreach (var c in byteValues)
                        {
                            list.Add(c.ToString(CultureInfo.InvariantCulture));
                        }
                    }
                    break;
                case "Char":
                    if (value is IEnumerable<char> charValues)
                    {
                        foreach (var c in charValues)
                        {
                            list.Add(c.ToString());
                        }
                    }
                    break;
                case "Int16":
                    isValueType = true;
                    if (value is IEnumerable<short> shortValues)
                    {
                        foreach (var c in shortValues)
                        {
                            list.Add(c.ToString());
                        }
                    }
                    break;
                case "Int32":
                    isValueType = true;
                    if (value is IEnumerable<int> intValues)
                    {
                        foreach (var c in intValues)
                        {
                            list.Add(c.ToString());
                        }
                    }
                    break;
                case "Int64":
                    isValueType = true;
                    if (value is IEnumerable<long> longValues)
                    {
                        foreach (var c in longValues)
                        {
                            list.Add(c.ToString());
                        }
                    }
                    break;
                case "Double":
                    isValueType = true;
                    if (value is IEnumerable<double> doubleValues)
                    {
                        foreach (var c in doubleValues)
                        {
                            list.Add(c.ToString(CultureInfo.InvariantCulture));
                        }
                    }
                    break;
                case "Single":
                    isValueType = true;
                    if (value is IEnumerable<float> floatValues)
                    {
                        foreach (var c in floatValues)
                        {
                            list.Add(c.ToString(CultureInfo.InvariantCulture));
                        }
                    }
                    break;
                case "Decimal":
                    isValueType = true;
                    if (value is IEnumerable<decimal> decimalValues)
                    {
                        foreach (var c in decimalValues)
                        {
                            list.Add(c.ToString(CultureInfo.InvariantCulture));
                        }
                    }
                    break;
            }
        }

        if (list!.Count < 1)
            return;

        sqlBuilder.Append(columnName);
        sqlBuilder.Append(notContainer ? " NOT IN (" : " IN (");

        //值类型不带引号
        if (isValueType)
        {
            for (var i = 0; i < list.Count; i++)
            {
                sqlBuilder.AppendFormat("{0}", list[i]);
                if (i != list.Count - 1)
                {
                    sqlBuilder.Append(",");
                }
            }
        }
        else
        {
            for (var i = 0; i < list.Count; i++)
            {
                sqlBuilder.AppendFormat("'{0}'", list[i].Replace("'", "''"));
                if (i != list.Count - 1)
                {
                    sqlBuilder.Append(",");
                }
            }
        }

        sqlBuilder.Append(")");
    }

19 View Source File : PermissionResolver.cs
License : MIT License
Project Creator : 17MKH

private void Load()
    {
        var controllers = _controllerResolver.Controllers;
        foreach (var controller in controllers)
        {
            if (!controller.Actions.Any())
                continue;

            foreach (var action in controller.Actions)
            {
                var permission = new PermissionDescriptor
                {
                    Action = action.Name,
                    Controller = controller.Name,
                    ModuleCode = controller.Area,
                    HttpMethod = HttpMethod.Get,
                    Mode = PermissionMode.Authorization
                };

                //请求方式
                var httpMethodAttr = action.MethodInfo.CustomAttributes.FirstOrDefault(m => typeof(HttpMethodAttribute).IsreplacedignableFrom(m.AttributeType));
                if (httpMethodAttr != null)
                {
                    var httpMethodName = httpMethodAttr.AttributeType.Name.Replace("Http", "").Replace("Attribute", "");
                    permission.HttpMethod = (HttpMethod)Enum.Parse(typeof(HttpMethod), httpMethodName);
                }

                #region ==权限模式==

                var allowAnonymousAttribute = action.MethodInfo.CustomAttributes.FirstOrDefault(m => typeof(AllowAnonymousAttribute) == m.AttributeType);
                if (allowAnonymousAttribute != null)
                {
                    permission.Mode = PermissionMode.Anonymous;
                }
                else
                {
                    var allowLoginAttribute = action.MethodInfo.CustomAttributes.FirstOrDefault(m => typeof(AllowWhenAuthenticatedAttribute) == m.AttributeType);
                    if (allowLoginAttribute != null)
                    {
                        permission.Mode = PermissionMode.Login;
                    }
                }

                #endregion

                _descriptors.Add(permission);
            }
        }
    }

19 View Source File : HttpClientAsync.cs
License : MIT License
Project Creator : 188867052

private static async Task<string> GetResponseMessageAsync(HttpClient httpClient, RouteInfo routeInfo, params object[] data)
        {
            HttpResponseMessage httpResponseMessage;
            StringContent httpContent;
            PrepareConstraintParameters(out string url, out IList<string> constraintNameList, routeInfo, data);
            var httpMethod = (HttpMethod)Enum.Parse(typeof(HttpMethod), routeInfo.HttpMethods, true);
            switch (httpMethod)
            {
                case HttpMethod.Get:
                    httpResponseMessage = await httpClient.GetAsync(url);
                    break;
                case HttpMethod.Post:
                    PrepareStringContent(out httpContent, constraintNameList, routeInfo, data);
                    httpResponseMessage = await httpClient.PostAsync(url, httpContent);
                    httpContent.Dispose();
                    break;
                case HttpMethod.Patch:
                    PrepareStringContent(out httpContent, constraintNameList, routeInfo, data);
                    httpResponseMessage = await httpClient.PatchAsync(url, httpContent);
                    httpContent.Dispose();
                    break;
                case HttpMethod.Delete:
                    httpResponseMessage = await httpClient.DeleteAsync(url);
                    break;
                case HttpMethod.Put:
                    PrepareStringContent(out httpContent, constraintNameList, routeInfo, data);
                    httpResponseMessage = await httpClient.PutAsync(url, httpContent);
                    httpContent.Dispose();
                    break;
                default:
                    throw new HttpRequestException($"Waiting for Support! Http Method: {httpMethod}.");
            }

            var message = await httpResponseMessage.Content.ReadreplacedtringAsync();
            httpResponseMessage.Dispose();
            return message;
        }

19 View Source File : DotNetToJScript.cs
License : MIT License
Project Creator : 1y0n

static void ParseEnum<T>(string name, out T value) where T : struct
        {
            value = (T)Enum.Parse(typeof(T), name, true);
        }

19 View Source File : SetPropertyAction.cs
License : MIT License
Project Creator : 1iveowl

private void UpdatePropertyValue(object targetObject)
        {
            var targetType = targetObject.GetType();
            var propertyInfo = targetType.GetRuntimeProperty(PropertyName);
            ValidateProperty(targetType.Name, propertyInfo);

            Exception innerException = null;
            try
            {
                object result;

                var propertyType = propertyInfo.PropertyType;
                var propertyTypeInfo = propertyType.GetTypeInfo();

                if (Value is null)
                {
                    result = propertyTypeInfo.IsValueType ? Activator.CreateInstance(propertyType) : null;
                }
                else if (propertyTypeInfo.IsreplacedignableFrom(Value.GetType().GetTypeInfo()))
                {
                    result = Value;
                }
                else
                {
                    var valuereplacedtring = Value.ToString();
                    result = propertyTypeInfo.IsEnum ? Enum.Parse(propertyType, valuereplacedtring, false) : TypeConverterHelper.Convert(valuereplacedtring, propertyType.FullName);
                }
                propertyInfo.SetValue(targetObject, result, new object[0]);
            }
            catch (FormatException ex)
            {
                innerException = ex;
            }
            catch (ArgumentException ex)
            {
                innerException = ex;
            }

            if (innerException != null)
            {
                throw new ArgumentException("Cannot set value.", innerException);
            }
        }

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

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

19 View Source File : DOTweenAnimationInspector.cs
License : MIT License
Project Creator : 39M

override public void OnInspectorGUI()
        {
        	base.OnInspectorGUI();

            GUILayout.Space(3);
            EditorGUIUtils.SetGUIStyles();

            bool playMode = Application.isPlaying;
            _runtimeEditMode = _runtimeEditMode && playMode;

            GUILayout.BeginHorizontal();
            EditorGUIUtils.InspectorLogo();
            GUILayout.Label(_src.animationType.ToString() + (string.IsNullOrEmpty(_src.id) ? "" : " [" + _src.id + "]"), EditorGUIUtils.sideLogoIconBoldLabelStyle);
            // Up-down buttons
            GUILayout.FlexibleSpace();
            if (GUILayout.Button("▲", DeGUI.styles.button.toolIco)) UnityEditorInternal.ComponentUtility.MoveComponentUp(_src);
            if (GUILayout.Button("▼", DeGUI.styles.button.toolIco)) UnityEditorInternal.ComponentUtility.MoveComponentDown(_src);
            GUILayout.EndHorizontal();

            if (playMode) {
                if (_runtimeEditMode) {
                    
                } else {
                    GUILayout.Space(8);
                    GUILayout.Label("Animation Editor disabled while in play mode", EditorGUIUtils.wordWrapLabelStyle);
                    if (!_src.isActive) {
                        GUILayout.Label("This animation has been toggled as inactive and won't be generated", EditorGUIUtils.wordWrapLabelStyle);
                        GUI.enabled = false;
                    }
                    if (GUILayout.Button(new GUIContent("Activate Edit Mode", "Switches to Runtime Edit Mode, where you can change animations values and restart them"))) {
                        _runtimeEditMode = true;
                    }
                    GUILayout.Label("NOTE: when using DOPlayNext, the sequence is determined by the DOTweenAnimation Components order in the target GameObject's Inspector", EditorGUIUtils.wordWrapLabelStyle);
                    GUILayout.Space(10);
                    if (!_runtimeEditMode) return;
                }
            }

            Undo.RecordObject(_src, "DOTween Animation");

//            _src.isValid = Validate(); // Moved down

            EditorGUIUtility.labelWidth = 110;

            if (playMode) {
                GUILayout.Space(4);
                DeGUILayout.Toolbar("Edit Mode Commands");
                DeGUILayout.BeginVBox(DeGUI.styles.box.stickyTop);
                    GUILayout.BeginHorizontal();
                    if (GUILayout.Button("TogglePause")) _src.tween.TogglePause();
                    if (GUILayout.Button("Rewind")) _src.tween.Rewind();
                    if (GUILayout.Button("Restart")) _src.tween.Restart();
                    GUILayout.EndHorizontal();
                    if (GUILayout.Button("Commit changes and restart")) {
                        _src.tween.Rewind();
                        _src.tween.Kill();
                        if (_src.isValid) {
                            _src.CreateTween();
                            _src.tween.Play();
                        }
                    }
                    GUILayout.Label("To apply your changes when exiting Play mode, use the Component's upper right menu and choose \"Copy Component\", then \"Paste Component Values\" after exiting Play mode", DeGUI.styles.label.wordwrap);
                DeGUILayout.EndVBox();
            } else {
                bool hasManager = _src.GetComponent<DOTweenVisualManager>() != null;
                if (!hasManager) {
                    if (GUILayout.Button(new GUIContent("Add Manager", "Adds a manager component which allows you to choose additional options for this gameObject"))) {
                        _src.gameObject.AddComponent<DOTweenVisualManager>();
                    }
                }
            }

            GUILayout.BeginHorizontal();
                DOTweenAnimationType prevAnimType = _src.animationType;
//                _src.animationType = (DOTweenAnimationType)EditorGUILayout.EnumPopup(_src.animationType, EditorGUIUtils.popupButton);
                _src.isActive = EditorGUILayout.Toggle(new GUIContent("", "If unchecked, this animation will not be created"), _src.isActive, GUILayout.Width(16));
                GUI.enabled = _src.isActive;
                _src.animationType = AnimationToDOTweenAnimationType(_AnimationType[EditorGUILayout.Popup(DOTweenAnimationTypeToPopupId(_src.animationType), _AnimationType)]);
                _src.autoPlay = DeGUILayout.ToggleButton(_src.autoPlay, new GUIContent("AutoPlay", "If selected, the tween will play automatically"));
                _src.autoKill = DeGUILayout.ToggleButton(_src.autoKill, new GUIContent("AutoKill", "If selected, the tween will be killed when it completes, and won't be reusable"));
            GUILayout.EndHorizontal();
            if (prevAnimType != _src.animationType) {
                // Set default optional values based on animation type
                _src.endValueTransform = null;
                _src.useTargetAsV3 = false;
                switch (_src.animationType) {
                case DOTweenAnimationType.Move:
                case DOTweenAnimationType.LocalMove:
                case DOTweenAnimationType.Rotate:
                case DOTweenAnimationType.LocalRotate:
                case DOTweenAnimationType.Scale:
                    _src.endValueV3 = Vector3.zero;
                    _src.endValueFloat = 0;
                    _src.optionalBool0 = _src.animationType == DOTweenAnimationType.Scale;
                    break;
                case DOTweenAnimationType.UIWidthHeight:
                    _src.endValueV3 = Vector3.zero;
                    _src.endValueFloat = 0;
                    _src.optionalBool0 = _src.animationType == DOTweenAnimationType.UIWidthHeight;
                    break;
                case DOTweenAnimationType.Color:
                case DOTweenAnimationType.Fade:
                    _isLightSrc = _src.GetComponent<Light>() != null;
                    _src.endValueFloat = 0;
                    break;
                case DOTweenAnimationType.Text:
                    _src.optionalBool0 = true;
                    break;
                case DOTweenAnimationType.PunchPosition:
                case DOTweenAnimationType.PunchRotation:
                case DOTweenAnimationType.PunchScale:
                    _src.endValueV3 = _src.animationType == DOTweenAnimationType.PunchRotation ? new Vector3(0,180,0) : Vector3.one;
                    _src.optionalFloat0 = 1;
                    _src.optionalInt0 = 10;
                    _src.optionalBool0 = false;
                    break;
                case DOTweenAnimationType.ShakePosition:
                case DOTweenAnimationType.ShakeRotation:
                case DOTweenAnimationType.ShakeScale:
                    _src.endValueV3 = _src.animationType == DOTweenAnimationType.ShakeRotation ? new Vector3(90,90,90) : Vector3.one;
                    _src.optionalInt0 = 10;
                    _src.optionalFloat0 = 90;
                    _src.optionalBool0 = false;
                    break;
                case DOTweenAnimationType.CameraAspect:
                case DOTweenAnimationType.CameraFieldOfView:
                case DOTweenAnimationType.CameraOrthoSize:
                    _src.endValueFloat = 0;
                    break;
                case DOTweenAnimationType.CameraPixelRect:
                case DOTweenAnimationType.CameraRect:
                    _src.endValueRect = new Rect(0, 0, 0, 0);
                    break;
                }
            }
            if (_src.animationType == DOTweenAnimationType.None) {
                _src.isValid = false;
                if (GUI.changed) EditorUtility.SetDirty(_src);
                return;
            }

            if (prevAnimType != _src.animationType || ComponentsChanged()) {
                _src.isValid = Validate();
                // See if we need to choose between multiple targets
                if (_src.animationType == DOTweenAnimationType.Fade && _src.GetComponent<CanvasGroup>() != null && _src.GetComponent<Image>() != null) {
                    _chooseTargetMode = ChooseTargetMode.BetweenCanvasGroupAndImage;
                    // Rereplacedign target and forcedTargetType if lost
                    if (_src.forcedTargetType == TargetType.Unset) _src.forcedTargetType = _src.targetType;
                    switch (_src.forcedTargetType) {
                    case TargetType.CanvasGroup:
                        _src.target = _src.GetComponent<CanvasGroup>();
                        break;
                    case TargetType.Image:
                        _src.target = _src.GetComponent<Image>();
                        break;
                    }
                } else {
                    _chooseTargetMode = ChooseTargetMode.None;
                    _src.forcedTargetType = TargetType.Unset;
                }
            }

            if (!_src.isValid) {
                GUI.color = Color.red;
                GUILayout.BeginVertical(GUI.skin.box);
                GUILayout.Label("No valid Component was found for the selected animation", EditorGUIUtils.wordWrapLabelStyle);
                GUILayout.EndVertical();
                GUI.color = Color.white;
                if (GUI.changed) EditorUtility.SetDirty(_src);
                return;
            }

            // Special cases in which multiple target types could be used (set after validation)
            if (_chooseTargetMode == ChooseTargetMode.BetweenCanvasGroupAndImage && _src.forcedTargetType != TargetType.Unset) {
                FadeTargetType fadeTargetType = (FadeTargetType)Enum.Parse(typeof(FadeTargetType), _src.forcedTargetType.ToString());
                TargetType prevTargetType = _src.forcedTargetType;
                _src.forcedTargetType = (TargetType)Enum.Parse(typeof(TargetType), EditorGUILayout.EnumPopup(_src.animationType + " Target", fadeTargetType).ToString());
                if (_src.forcedTargetType != prevTargetType) {
                    // Target type change > replacedign correct target
                    switch (_src.forcedTargetType) {
                    case TargetType.CanvasGroup:
                        _src.target = _src.GetComponent<CanvasGroup>();
                        break;
                    case TargetType.Image:
                        _src.target = _src.GetComponent<Image>();
                        break;
                    }
                }
            }

            GUILayout.BeginHorizontal();
            _src.duration = EditorGUILayout.FloatField("Duration", _src.duration);
            if (_src.duration < 0) _src.duration = 0;
            _src.isSpeedBased = DeGUILayout.ToggleButton(_src.isSpeedBased, new GUIContent("SpeedBased", "If selected, the duration will count as units/degree x second"), DeGUI.styles.button.tool, GUILayout.Width(75));
            GUILayout.EndHorizontal();
            _src.delay = EditorGUILayout.FloatField("Delay", _src.delay);
            if (_src.delay < 0) _src.delay = 0;
            _src.isIndependentUpdate = EditorGUILayout.Toggle("Ignore TimeScale", _src.isIndependentUpdate);
            _src.easeType = EditorGUIUtils.FilteredEasePopup(_src.easeType);
            if (_src.easeType == Ease.INTERNAL_Custom) {
                _src.easeCurve = EditorGUILayout.CurveField("   Ease Curve", _src.easeCurve);
            }
            _src.loops = EditorGUILayout.IntField(new GUIContent("Loops", "Set to -1 for infinite loops"), _src.loops);
            if (_src.loops < -1) _src.loops = -1;
            if (_src.loops > 1 || _src.loops == -1)
                _src.loopType = (LoopType)EditorGUILayout.EnumPopup("   Loop Type", _src.loopType);
            _src.id = EditorGUILayout.TextField("ID", _src.id);

            bool canBeRelative = true;
            // End value and eventual specific options
            switch (_src.animationType) {
            case DOTweenAnimationType.Move:
            case DOTweenAnimationType.LocalMove:
                GUIEndValueV3(_src.animationType == DOTweenAnimationType.Move);
                _src.optionalBool0 = EditorGUILayout.Toggle("    Snapping", _src.optionalBool0);
                canBeRelative = !_src.useTargetAsV3;
                break;
            case DOTweenAnimationType.Rotate:
            case DOTweenAnimationType.LocalRotate:
                if (_src.GetComponent<Rigidbody2D>()) GUIEndValueFloat();
                else {
                    GUIEndValueV3();
                    _src.optionalRotationMode = (RotateMode)EditorGUILayout.EnumPopup("    Rotation Mode", _src.optionalRotationMode);
                }
                break;
            case DOTweenAnimationType.Scale:
                if (_src.optionalBool0) GUIEndValueFloat();
                else GUIEndValueV3();
                _src.optionalBool0 = EditorGUILayout.Toggle("Uniform Scale", _src.optionalBool0);
                break;
            case DOTweenAnimationType.UIWidthHeight:
                if (_src.optionalBool0) GUIEndValueFloat();
                else GUIEndValueV2();
                _src.optionalBool0 = EditorGUILayout.Toggle("Uniform Scale", _src.optionalBool0);
                break;
            case DOTweenAnimationType.Color:
                GUIEndValueColor();
                canBeRelative = false;
                break;
            case DOTweenAnimationType.Fade:
                GUIEndValueFloat();
                if (_src.endValueFloat < 0) _src.endValueFloat = 0;
                if (!_isLightSrc && _src.endValueFloat > 1) _src.endValueFloat = 1;
                canBeRelative = false;
                break;
            case DOTweenAnimationType.Text:
                GUIEndValueString();
                _src.optionalBool0 = EditorGUILayout.Toggle("Rich Text Enabled", _src.optionalBool0);
                _src.optionalScrambleMode = (ScrambleMode)EditorGUILayout.EnumPopup("Scramble Mode", _src.optionalScrambleMode);
                _src.optionalString = EditorGUILayout.TextField(new GUIContent("Custom Scramble", "Custom characters to use in case of ScrambleMode.Custom"), _src.optionalString);
                break;
            case DOTweenAnimationType.PunchPosition:
            case DOTweenAnimationType.PunchRotation:
            case DOTweenAnimationType.PunchScale:
                GUIEndValueV3();
                canBeRelative = false;
                _src.optionalInt0 = EditorGUILayout.IntSlider(new GUIContent("    Vibrato", "How much will the punch vibrate"), _src.optionalInt0, 1, 50);
                _src.optionalFloat0 = EditorGUILayout.Slider(new GUIContent("    Elasticity", "How much the vector will go beyond the starting position when bouncing backwards"), _src.optionalFloat0, 0, 1);
                if (_src.animationType == DOTweenAnimationType.PunchPosition) _src.optionalBool0 = EditorGUILayout.Toggle("    Snapping", _src.optionalBool0);
                break;
            case DOTweenAnimationType.ShakePosition:
            case DOTweenAnimationType.ShakeRotation:
            case DOTweenAnimationType.ShakeScale:
                GUIEndValueV3();
                canBeRelative = false;
                _src.optionalInt0 = EditorGUILayout.IntSlider(new GUIContent("    Vibrato", "How much will the shake vibrate"), _src.optionalInt0, 1, 50);
                _src.optionalFloat0 = EditorGUILayout.Slider(new GUIContent("    Randomness", "The shake randomness"), _src.optionalFloat0, 0, 90);
                if (_src.animationType == DOTweenAnimationType.ShakePosition) _src.optionalBool0 = EditorGUILayout.Toggle("    Snapping", _src.optionalBool0);
                break;
            case DOTweenAnimationType.CameraAspect:
            case DOTweenAnimationType.CameraFieldOfView:
            case DOTweenAnimationType.CameraOrthoSize:
                GUIEndValueFloat();
                canBeRelative = false;
                break;
            case DOTweenAnimationType.CameraBackgroundColor:
                GUIEndValueColor();
                canBeRelative = false;
                break;
            case DOTweenAnimationType.CameraPixelRect:
            case DOTweenAnimationType.CameraRect:
                GUIEndValueRect();
                canBeRelative = false;
                break;
            }

            // Final settings
            if (canBeRelative) _src.isRelative = EditorGUILayout.Toggle("    Relative", _src.isRelative);

            // Events
            AnimationInspectorGUI.AnimationEvents(this, _src);

            if (GUI.changed) EditorUtility.SetDirty(_src);
        }

19 View Source File : Helpers.cs
License : MIT License
Project Creator : 404Lcc

internal static object ParseEnum(Type type, string value)
        {
#if FEAT_IKVM
            FieldInfo[] fields = type.GetFields();
            foreach (FieldInfo field in fields)
            {
                if (string.Equals(field.Name, value, StringComparison.OrdinalIgnoreCase)) return field.GetRawConstantValue();
            }
            throw new ArgumentException("Enum value could not be parsed: " + value + ", " + type.FullName);
#else
            return Enum.Parse(type, value, true);
#endif
        }

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

private async Task<ResultModel> CheckQuestIfComplete(PlayerEnreplacedy player, string targetStr)
        {
            var result = new ResultModel { IsSuccess = false };

            if (!string.IsNullOrEmpty(targetStr))
            {
                List<QuestTarget> questTargets = new List<QuestTarget>();
                try
                {
                    questTargets = JsonConvert.DeserializeObject<List<QuestTarget>>(targetStr);
                }
                catch (Exception ex)
                {
                    _logger.LogError($"Convert QuestTarget:{ex}");
                }

                foreach (var questTarget in questTargets)
                {
                    var npcId = questTarget.Attrs.FirstOrDefault(x => x.Attr == "NpcId")?.Val;
                    var questId = questTarget.Attrs.FirstOrDefault(x => x.Attr == "QuestId")?.Val;
                    int.TryParse(questTarget.Attrs.FirstOrDefault(x => x.Attr == "RoomId")?.Val, out int roomId);

                    var targetEnum = (QuestTargetEnum)Enum.Parse(typeof(QuestTargetEnum), questTarget.Target, true);


                    switch (targetEnum)
                    {


                        case QuestTargetEnum.与某个Npc对话:
                            if (await _redisDb.StringGet<int>(string.Format(RedisKey.ChatWithNpc, player.Id, npcId)) != 1)
                            {
                                result.ErrorMessage = $"";
                                return result;
                            }
                            break;

                        case QuestTargetEnum.所在房间:
                            if (player.RoomId != roomId)
                            {
                                result.ErrorMessage = "";
                                return result;
                            }


                            break;

                    }
                }
            }





            result.IsSuccess = true;
            return result;
        }

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

private async Task<ResultModel> DoQuestConsume(PlayerEnreplacedy player, string consumeStr)
        {
            var result = new ResultModel
            {
                IsSuccess = false
            };
            if (!string.IsNullOrEmpty(consumeStr))
            {
                List<QuestConsume> questConsumes = new List<QuestConsume>();
                try
                {
                    questConsumes = JsonConvert.DeserializeObject<List<QuestConsume>>(consumeStr);
                }
                catch (Exception ex)
                {
                    _logger.LogError($"Convert QuestConsume:{ex}");
                }

                foreach (var questConsume in questConsumes)
                {
                    var npcId = questConsume.Attrs.FirstOrDefault(x => x.Attr == "NpcId")?.Val;
                    int.TryParse(questConsume.Attrs.FirstOrDefault(x => x.Attr == "Exp")?.Val, out int exp);
                    long.TryParse(questConsume.Attrs.FirstOrDefault(x => x.Attr == "Money")?.Val, out long money);

                    var consumeEnum = (QuestConsumeEnum)Enum.Parse(typeof(QuestConsumeEnum), questConsume.Consume, true);


                    switch (consumeEnum)
                    {


                        case QuestConsumeEnum.物品:

                            //TODO 减少物品
                            return result;

                        case QuestConsumeEnum.经验:
                            player.Exp -= exp;
                            break;

                        case QuestConsumeEnum.金钱:
                            player.Money -= money;
                            break;


                    }

                }

                await _playerDomainService.Update(player);
            }

            result.IsSuccess = true;
            return await Task.FromResult(result);
        }

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

private async Task DoCommand(PlayerEnreplacedy player, NpcEnreplacedy npc, int scriptId, string command, List<CaseAttribute> attrs, string input)
        {
            var replacedle = attrs.FirstOrDefault(x => x.Attr == "replacedle")?.Val;
            var message = attrs.FirstOrDefault(x => x.Attr == "Message")?.Val;
            var tips = attrs.FirstOrDefault(x => x.Attr == "Tips")?.Val;
            int.TryParse(attrs.FirstOrDefault(x => x.Attr == "CommandId")?.Val, out int commandId);
            int.TryParse(attrs.FirstOrDefault(x => x.Attr == "QuestId")?.Val, out int questId);



            var key = $"commandIds_{player.Id}_{npc.Id}_{scriptId}";
            var commandIds = await _redisDb.StringGet<List<int>>(key) ?? new List<int>();
            if (commandId > 0 && !commandIds.Contains(commandId))
            {
                commandIds.Add(commandId);
            }

            await _redisDb.StringSet(key, commandIds);

            var commandEnum = (CommandTypeEnum)Enum.Parse(typeof(CommandTypeEnum), command, true);

            //await _bus.RaiseEvent(new DomainNotification($"command= {command}"));
            switch (commandEnum)
            {
                case CommandTypeEnum.播放对话:
                    await _mudProvider.ShowMessage(player.Id, $"{npc.Name}:{message}", MessageTypeEnum.聊天);
                    break;

                case CommandTypeEnum.对话选项:
                    await _mudProvider.ShowMessage(player.Id, $" → <a href='javascript:;' clreplaced='chat' npcId='{npc.Id}' scriptId='{scriptId}' commandId='{commandId}'>{replacedle}</a><br />", MessageTypeEnum.指令);
                    break;

                case CommandTypeEnum.输入选项:
                    await _mudProvider.ShowMessage(player.Id, $" → <a href = 'javascript:;'>{tips}</a>  <input type = 'text' name='input' style='width:120px;margin-left:10px;' />  <button type = 'button' clreplaced='input' style='padding:1px 3px;' npcId='{npc.Id}'  scriptId='{scriptId}'  commandId='{commandId}'> 确定 </button><br />", MessageTypeEnum.指令);
                    break;

                case CommandTypeEnum.跳转到分支:
                    await DoScript(player, npc, scriptId, commandId);
                    break;


                case CommandTypeEnum.领取任务:
                    await TakeQuest(player, questId);
                    break;

                case CommandTypeEnum.完成任务:
                    await ComplateQuest(player, questId);
                    break;
            }
        }

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

private List<int> GetRelations(string relation)
        {
            List<int> relations = new List<int>();// 1 大于,0 等于 ,-1 小于
            var relationEnum = (LogicalRelationTypeEnum)Enum.Parse(typeof(LogicalRelationTypeEnum), relation, true);
            switch (relationEnum)
            {
                case LogicalRelationTypeEnum.不等于:
                    relations = new List<int>() { 1, -1 };
                    break;

                case LogicalRelationTypeEnum.大于:
                    relations = new List<int>() { 1 };
                    break;

                case LogicalRelationTypeEnum.大于等于:
                    relations = new List<int>() { 1, 0 };
                    break;

                case LogicalRelationTypeEnum.小于:
                    relations = new List<int>() { -1 };
                    break;

                case LogicalRelationTypeEnum.小于等于:
                    relations = new List<int>() { 0, -1 };
                    break;

                case LogicalRelationTypeEnum.等于:
                    relations = new List<int>() { 0 };
                    break;
            }

            return relations;
        }

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

private async Task<ResultModel> TakeQuestReward(PlayerEnreplacedy player, string rewardStr)
        {
            var result = new ResultModel
            {
                IsSuccess = false
            };
            if (!string.IsNullOrEmpty(rewardStr))
            {
                List<QuestReward> questRewards = new List<QuestReward>();
                try
                {
                    questRewards = JsonConvert.DeserializeObject<List<QuestReward>>(rewardStr);
                }
                catch (Exception ex)
                {
                    _logger.LogError($"Convert QuestReward:{ex}");
                }

                foreach (var questReward in questRewards)
                {
                    int.TryParse(questReward.Attrs.FirstOrDefault(x => x.Attr == "NpcId")?.Val, out int npcId);
                    int.TryParse(questReward.Attrs.FirstOrDefault(x => x.Attr == "Exp")?.Val, out int exp);
                    long.TryParse(questReward.Attrs.FirstOrDefault(x => x.Attr == "Money")?.Val, out long money);
                    int.TryParse(questReward.Attrs.FirstOrDefault(x => x.Attr == "WareId")?.Val, out int wareId);
                    int.TryParse(questReward.Attrs.FirstOrDefault(x => x.Attr == "Number")?.Val, out int number);

                    var rewardEnum = (QuestRewardEnum)Enum.Parse(typeof(QuestRewardEnum), questReward.Reward, true);


                    switch (rewardEnum)
                    {


                        case QuestRewardEnum.物品:
                            var ware = await _wareDomainService.Get(wareId);
                            if (ware != null)
                            {
                                await _mudProvider.ShowMessage(player.Id, $"获得 {number}{ware.Unit}[{ware.Name}]");
                            }
                            // 添加物品

                            break;

                        case QuestRewardEnum.经验:
                            player.Exp += exp;
                            await _mudProvider.ShowMessage(player.Id, $"获得经验 +{exp}");
                            break;

                        case QuestRewardEnum.金钱:
                            player.Money += money;
                            await _mudProvider.ShowMessage(player.Id, $"获得 +{money.ToMoney()}");
                            break;


                    }

                }

                await _playerDomainService.Update(player);
            }

            result.IsSuccess = true;
            return await Task.FromResult(result);
        }

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

private async Task<ResultModel> CheckTakeCondition(PlayerEnreplacedy player, string takeConditionStr)
        {
            var result = new ResultModel { IsSuccess = false };

            if (!string.IsNullOrEmpty(takeConditionStr))
            {
                List<QuestTakeCondition> takeConditions = new List<QuestTakeCondition>();
                try
                {
                    takeConditions = JsonConvert.DeserializeObject<List<QuestTakeCondition>>(takeConditionStr);
                }
                catch (Exception ex)
                {
                    _logger.LogError($"Convert CaseIf:{ex}");
                }

                foreach (var takeCondition in takeConditions)
                {
                    var npcId = takeCondition.Attrs.FirstOrDefault(x => x.Attr == "NpcId")?.Val;
                    var questId = takeCondition.Attrs.FirstOrDefault(x => x.Attr == "QuestId")?.Val;
                    int.TryParse(takeCondition.Attrs.FirstOrDefault(x => x.Attr == "RoomId")?.Val, out int roomId);

                    var targetEnum = (QuestTakeConditionEnum)Enum.Parse(typeof(QuestTakeConditionEnum), takeCondition.Condition, true);


                    switch (targetEnum)
                    {


                        case QuestTakeConditionEnum.与某个Npc对话:
                            if (await _redisDb.StringGet<int>(string.Format(RedisKey.ChatWithNpc, player.Id, npcId)) != 1)
                            {
                                result.ErrorMessage = $"";
                                return result;
                            }
                            break;

                        case QuestTakeConditionEnum.完成前置任务:

                            if (await _redisDb.StringGet<int>(string.Format(RedisKey.CompleteQuest, player.Id, questId)) != 1)
                            {
                                result.ErrorMessage = $"";
                                return result;
                            }

                            break;


                    }
                }
            }




            result.IsSuccess = true;
            return result;
        }

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

private PropertyInfo GetFieldPropertyInfo(PlayerEnreplacedy player, string field)
        {
            var fieldEnum = (PlayerConditionFieldEnum)Enum.Parse(typeof(PlayerConditionFieldEnum), field, true);


            var key = $"player_properties";
            var properties = _cache.GetOrCreate(key, p => {
                p.SetAbsoluteExpiration(TimeSpan.FromHours(24));
                return player.GetType().GetProperties();
            });

            foreach (var prop in properties)
            {
                var attribute = prop.GetCustomAttributes(typeof(ConditionFieldAttribute), true).FirstOrDefault();
                if (attribute != null)
                {
                    if ((attribute as ConditionFieldAttribute).FieldEnum == fieldEnum)
                    {
                        return prop;
                    }
                }
            }

            return null;
        }

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

private async Task<ResultModel> CheckQuestConsume(PlayerEnreplacedy player, string consumeStr)
        {
            var result = new ResultModel
            {
                IsSuccess = false
            };
            if (!string.IsNullOrEmpty(consumeStr))
            {
                List<QuestConsume> questConsumes = new List<QuestConsume>();
                try
                {
                    questConsumes = JsonConvert.DeserializeObject<List<QuestConsume>>(consumeStr);
                }
                catch (Exception ex)
                {
                    _logger.LogError($"Convert QuestConsume:{ex}");
                }

                foreach (var questConsume in questConsumes)
                {
                    var npcId = questConsume.Attrs.FirstOrDefault(x => x.Attr == "NpcId")?.Val;
                    int.TryParse(questConsume.Attrs.FirstOrDefault(x => x.Attr == "Exp")?.Val, out int exp);
                    long.TryParse(questConsume.Attrs.FirstOrDefault(x => x.Attr == "Money")?.Val, out long money);

                    var consumeEnum = (QuestConsumeEnum)Enum.Parse(typeof(QuestConsumeEnum), questConsume.Consume, true);


                    switch (consumeEnum)
                    {


                        case QuestConsumeEnum.物品:

                            //TODO
                            result.ErrorMessage = $"完成任务需要消耗物品";
                            return result;

                        case QuestConsumeEnum.经验:
                            if (player.Exp < exp)
                            {
                                result.ErrorMessage = $"完成任务需要消耗经验 {exp}";
                                return result;
                            }
                            break;

                        case QuestConsumeEnum.金钱:
                            if (player.Money < money)
                            {
                                result.ErrorMessage = $"完成任务需要消耗 {money.ToMoney()}";
                                return result;
                            }

                            break;


                    }

                }
            }

            result.IsSuccess = true;
            return await Task.FromResult(result);
        }

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

public async Task Handle(QuestTriggerEvent message, CancellationToken cancellationToken)
        {
            var player = message.Player;
            var questTriggerType = message.QuestTriggerType;

            //已经领取的所有任务
            var myQuests = (await _playerQuestDomainService.GetPlayerQuests(player.Id));
            //正在进行的任务
            var myQuestsNotComplete = myQuests.Where(x => x.Status== QuestStateEnum.已领取进行中);
            //所有未完成任务
            var quests = (await _questDomainService.GetAll()).Where(x => myQuestsNotComplete.Select(y => y.QuestId).Contains(x.Id));


            foreach(var quest in quests)
            {
                List<QuestTarget> questTargets = new List<QuestTarget>();
                try
                {
                    questTargets = JsonConvert.DeserializeObject<List<QuestTarget>>(quest.Target);
                }
                catch (Exception ex)
                {
                    _logger.LogError($"Convert QuestTarget:{ex}");
                }

                if (questTargets == null || questTargets.Count == 0)
                {
                    continue;
                }

                if (!questTargets.Exists(x => x.Target == questTriggerType.ToString()))
                {
                    continue;
                }

                foreach (var questTarget in questTargets)
                {
                    var npcId = questTarget.Attrs.FirstOrDefault(x => x.Attr == "NpcId")?.Val;
                    var questId = questTarget.Attrs.FirstOrDefault(x => x.Attr == "QuestId")?.Val;
                    int.TryParse(questTarget.Attrs.FirstOrDefault(x => x.Attr == "RoomId")?.Val, out int roomId);

                    var targetEnum = (QuestTargetEnum)Enum.Parse(typeof(QuestTargetEnum), questTarget.Target, true);
                    switch (targetEnum)
                    {

                        case QuestTargetEnum.与某个Npc对话:
    
                            break;

                        case QuestTargetEnum.所在房间:
                            if (player.RoomId != roomId)
                            {
                                continue;
                            }


                            break;

                    }
                }


            }


        }

19 View Source File : ChartLegendsExampleView.xaml.cs
License : MIT License
Project Creator : ABTSoftware

private void OnLegendModeChanged(object sender, SelectionChangedEventArgs e)
        {
            if (legendModifier != null)
            {
                legendModifier.GetLegendDataFor = (SourceMode)Enum.Parse(typeof(SourceMode), (string)e.AddedItems[0], true);
            }
        }

19 View Source File : ChartLegendsExampleView.xaml.cs
License : MIT License
Project Creator : ABTSoftware

private void OnLegendPlacementChanged(object sender, SelectionChangedEventArgs e)
        {
            if (legendModifier != null)
            {
                legendModifier.LegendPlacement = (LegendPlacement)Enum.Parse(typeof(LegendPlacement), (string)e.AddedItems[0], true);
            }
        }

19 View Source File : ChartLegendsExampleView.xaml.cs
License : MIT License
Project Creator : ABTSoftware

private void OnLegendOrientationChanged(object sender, SelectionChangedEventArgs e)
        {
            if (legendModifier != null)
            {
                legendModifier.Orientation = (Orientation)Enum.Parse(typeof(Orientation), (string)e.AddedItems[0], true);
            }
        }

19 View Source File : ChartLegendsExampleView.xaml.cs
License : MIT License
Project Creator : ABTSoftware

private void OnLegendHorizontalAlignmentChanged(object sender, SelectionChangedEventArgs e)
        {
            if (legendModifier != null)
            {
                legendModifier.HorizontalAlignment = (HorizontalAlignment)Enum.Parse(typeof(HorizontalAlignment), (string)e.AddedItems[0], true);
            }
        }

19 View Source File : ChartLegendsExampleView.xaml.cs
License : MIT License
Project Creator : ABTSoftware

private void OnLegendVerticalAlignmentChanged(object sender, SelectionChangedEventArgs e)
        {
            if (legendModifier != null)
            {
                legendModifier.VerticalAlignment = (VerticalAlignment)Enum.Parse(typeof(VerticalAlignment), (string)e.AddedItems[0], true);
            }
        }

19 View Source File : PolarChartExampleView.xaml.cs
License : MIT License
Project Creator : ABTSoftware

private void OnXAxisAlignmentChanged(object sender, SelectionChangedEventArgs e)
        {
            if (xAxis != null)
                xAxis.AxisAlignment = (AxisAlignment) Enum.Parse(typeof(AxisAlignment), (string) e.AddedItems[0], true);
        }

19 View Source File : PolarChartExampleView.xaml.cs
License : MIT License
Project Creator : ABTSoftware

private void OnYAxisAlignmentChanged(object sender, SelectionChangedEventArgs e)
        {
            if (yAxis != null)
                yAxis.AxisAlignment = (AxisAlignment) Enum.Parse(typeof(AxisAlignment), (string) e.AddedItems[0], true);
        }

19 View Source File : DragAxisToScale.xaml.cs
License : MIT License
Project Creator : ABTSoftware

private void DragModes_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (!_initialized) return;

            var mode = (AxisDragModes)Enum.Parse(typeof(AxisDragModes), (string)dragModes.SelectedValue, true);
            yAxisLeftDragmodifier.DragMode = mode;
            yAxisRightDragmodifier.DragMode = mode;
            xAxisDragModifier.DragMode = mode;
        }

19 View Source File : DragAxisToScale.xaml.cs
License : MIT License
Project Creator : ABTSoftware

private void DragXYDirection_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (!_initialized) return;

            switch ((XyDirection)Enum.Parse(typeof(XyDirection), (string)dragXYDirection.SelectedValue, true))
            {
                case XyDirection.XDirection:
                    yAxisLeftDragmodifier.IsEnabled = false;
                    yAxisRightDragmodifier.IsEnabled = false;
                    xAxisDragModifier.IsEnabled = true;
                    break;
                case XyDirection.YDirection:
                    yAxisLeftDragmodifier.IsEnabled = true;
                    yAxisRightDragmodifier.IsEnabled = true;
                    xAxisDragModifier.IsEnabled = false;
                    break;
                case XyDirection.XYDirection:
                    yAxisLeftDragmodifier.IsEnabled = true;
                    yAxisRightDragmodifier.IsEnabled = true;
                    xAxisDragModifier.IsEnabled = true;
                    break;
                case XyDirection.None:
                    yAxisLeftDragmodifier.IsEnabled = false;
                    yAxisRightDragmodifier.IsEnabled = false;
                    xAxisDragModifier.IsEnabled = false;
                    break;
            }
        }

19 View Source File : IsModifierTypeConverter.cs
License : MIT License
Project Creator : ABTSoftware

public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            var chartType = (ModifierType)value;
            var parameterType = (ModifierType)Enum.Parse(typeof(ModifierType), (string)parameter, true);

            return parameterType == chartType;
        }

19 View Source File : IsChartTypeConverter.cs
License : MIT License
Project Creator : ABTSoftware

public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            var chartType = (ChartType)value;
            var parameterType = (ChartType) Enum.Parse(typeof(ChartType), (string)parameter, true);

            return parameterType == chartType;
        }

19 View Source File : FifoLineSeriesSpeedTest.xaml.cs
License : MIT License
Project Creator : ABTSoftware

public void Execute(TestParameters testParameters, TimeSpan duration, Action<double> fpsResult)
        {
            _generator = new RandomLinesGenerator();
            var initialData = _generator.GetRandomLinesSeries(testParameters.PointCount);
            Random random = new Random(); 
            for (int i = 0; i < SeriesCount; i++)
            {
                // Setup
                _xyDataSeries = new XyDataSeries<double, double>() { FifoCapacity = testParameters.PointCount, DataDistributionCalculator = d };
                
                _listSeries.Add(_xyDataSeries);

                var rgb = new byte[3];
                random.NextBytes(rgb);
                _xyDataSeries.Append(initialData.XData, ScaleAndOffset(initialData.YData, 0.1, (double)i*0.2));
                var tmp = new SciChart.Charting.Visuals.RenderableSeries.FastLineRenderableSeries();
                tmp.DataSeries = _xyDataSeries;
                tmp.AntiAliasing = testParameters.AntiAliasing;
                tmp.Stroke  = System.Windows.Media.Color.FromArgb(255, rgb[0], rgb[1], rgb[2]);
                tmp.ResamplingMode = (ResamplingMode)Enum.Parse(typeof(ResamplingMode), testParameters.SamplingMode.ToString());
                sciChart.RenderableSeries.Add(tmp);
            }

            // Execute
           if (testParameters.TestRunner == TestRunnerType.Composition)
               _testRunner = new CompositionTestRunner(duration, OnAppendData, fpsResult);
           else
               _testRunner = new DispatcherTimerRunner(duration, OnAppendData, fpsResult);



           sciChart.Rendered += _testRunner.OnSciChartRendered;
            _testRunner.Run();
        }

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

public override Post ApplyTo(Post data)
        {
            if (id is not null)
                data = data with { Id = id };
            if (replacedle is not null)
                data = data with { replacedle = replacedle };
            if (category is not null)
                data = data with { Category = new Category { Items = category } };
            if (keywords is not null)
                data = data with { Keywords = new Keyword { Items = keywords } };
            if (DateTimeOffset.TryParse(creationTime, out var _creationTime))
            {
                data = data with { CreationTime = _creationTime };
            }
            if (DateTimeOffset.TryParse(modificationTime, out var _modificationTime))
            {
                data = data with { ModificationTime = _modificationTime };
            }
            if (type is not null)
                data = data with { Type = Enum.Parse<PostType>(type, true) };
            if (author is not null)
                data = data with { Author = author };
            return data;
        }

19 View Source File : Monster_Combat.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

public virtual void TakeDamageOverTime(float amount, DamageType damageType)
        {
            if (IsDead) return;

            TakeDamage(null, damageType, amount);

            // splatter effects
            var hitSound = new GameMessageSound(Guid, Sound.HitFlesh1, 0.5f);
            //var splatter = (PlayScript)Enum.Parse(typeof(PlayScript), "Splatter" + playerSource.GetSplatterHeight() + playerSource.GetSplatterDir(this));
            var splatter = new GameMessageScript(Guid, damageType == DamageType.Nether ? PlayScript.HealthDownVoid : PlayScript.DirtyFightingDamageOverTime);
            EnqueueBroadcast(hitSound, splatter);

            if (Health.Current <= 0) return;

            if (amount >= Health.MaxValue * 0.25f)
            {
                var painSound = (Sound)Enum.Parse(typeof(Sound), "Wound" + ThreadSafeRandom.Next(1, 3), true);
                EnqueueBroadcast(new GameMessageSound(Guid, painSound, 1.0f));
            }
        }

19 View Source File : Monster_Combat.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

public void EmitSplatter(Creature target, float damage)
        {
            if (target.IsDead) return;

            target.EnqueueBroadcast(new GameMessageSound(target.Guid, Sound.HitFlesh1, 0.5f));
            if (damage >= target.Health.MaxValue * 0.25f)
            {
                var painSound = (Sound)Enum.Parse(typeof(Sound), "Wound" + ThreadSafeRandom.Next(1, 3), true);
                target.EnqueueBroadcast(new GameMessageSound(target.Guid, painSound, 1.0f));
            }
            var splatter = (PlayScript)Enum.Parse(typeof(PlayScript), "Splatter" + GetSplatterHeight() + GetSplatterDir(target));
            target.EnqueueBroadcast(new GameMessageScript(target.Guid, splatter));
        }

19 View Source File : DictionaryExtensions.cs
License : MIT License
Project Creator : actions

public static bool TryGetEnum<T>(this IDictionary<string, object> dictionary, string key, out T value)
        {
            value = default(T);

            object objValue = null;

            if (dictionary.TryGetValue(key, out objValue))
            {
                if (objValue is string)
                {
                    try
                    {
                        value = (T)Enum.Parse(typeof(T), (string)objValue, true);
                        return true;
                    }
                    catch (ArgumentException)
                    {
                        // Provided string is not a member of enumeration
                    }
                }
                else
                {
                    try
                    {
                        value = (T)objValue;
                        return true;
                    }
                    catch (InvalidCastException)
                    {
                        // Value cannot be cast to the enum
                    }
                }
            }

            return false;
        }

19 View Source File : FlagsEnum.cs
License : MIT License
Project Creator : actions

public static object ParseKnownFlags(Type enumType, string stringValue)
        {
            ArgumentUtility.CheckForNull(enumType, nameof(enumType));
            if (!enumType.IsEnum)
            {
                throw new ArgumentException(PipelinesWebApiResources.FlagEnumTypeRequired());
            }

            // Check for the flags attribute in debug. Skip this reflection in release.
            Debug.replacedert(enumType.GetCustomAttributes(typeof(FlagsAttribute), inherit: false).Any(), "FlagsEnum only intended for enums with the Flags attribute.");

            // The exception types below are based on Enum.TryParseEnum (http://index/?query=TryParseEnum&rightProject=mscorlib&file=system%5Cenum.cs&rightSymbol=bhaeh2vnegwo)
            if (stringValue == null)
            {
                throw new ArgumentNullException(stringValue);
            }

            if (String.IsNullOrWhiteSpace(stringValue))
            {
                throw new ArgumentException(PipelinesWebApiResources.NonEmptyEnumElementsRequired(stringValue));
            }

            if (UInt64.TryParse(stringValue, NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out ulong ulongValue))
            {
                return Enum.Parse(enumType, stringValue);
            }

            var enumNames = Enum.GetNames(enumType).ToHashSet(name => name, StringComparer.OrdinalIgnoreCase);
            var enumMemberMappings = new Lazy<IDictionary<string, string>>(() =>
            {
                IDictionary<string, string> mappings = null;
                foreach (var field in enumType.GetFields())
                {
                    if (field.GetCustomAttributes(typeof(EnumMemberAttribute), false).FirstOrDefault() is EnumMemberAttribute enumMemberAttribute)
                    {
                        if (mappings == null)
                        {
                            mappings = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
                        }
                        mappings.Add(enumMemberAttribute.Value, field.GetValue(null).ToString());
                    }
                }

                return mappings;
            });

            var values = stringValue.Split(s_enumSeparatorCharArray);

            var matches = new List<string>();
            for (int i = 0; i < values.Length; i++)
            {
                string value = values[i].Trim();

                if (String.IsNullOrEmpty(value))
                {
                    throw new ArgumentException(PipelinesWebApiResources.NonEmptyEnumElementsRequired(stringValue));
                }

                if (enumNames.Contains(value))
                {
                    matches.Add(value);
                }
                else if (enumMemberMappings.Value != null && enumMemberMappings.Value.TryGetValue(value, out string matchingValue))
                {
                    matches.Add(matchingValue);
                }
            }

            if (!matches.Any())
            {
                return Enum.Parse(enumType, "0");
            }

            string matchesString = String.Join(", ", matches);
            return Enum.Parse(enumType, matchesString, ignoreCase: true);
        }

19 View Source File : VssCamelCasePropertyNamesContractResolver.cs
License : MIT License
Project Creator : actions

protected override JsonDictionaryContract CreateDictionaryContract(Type type)
        {
            // We need to preserve case for keys in the PropertiesCollection and optionally use integer values for enum keys
            JsonDictionaryContract contract = base.CreateDictionaryContract(type);

            Type keyType = contract.DictionaryKeyType;
            Boolean isEnumKey = keyType != null ? keyType.IsEnum : false;

            if (isEnumKey)
            {
                contract.DictionaryKeyResolver = (name) => ((int)Enum.Parse(keyType, name)).ToString();
            }
            else
            {
                contract.DictionaryKeyResolver = (name) => name;
            }

            return contract;
        }

19 View Source File : FlowSwitch.cs
License : GNU General Public License v3.0
Project Creator : Adam-Wilkinson

private INodeComponent GenerateSwitchesFor(ITypeDefinition typeDef)
        {
            if (typeDef.ValueType.IsEnum)
            {
                return Constructor.NodeComponentList(Enum.GetNames(typeDef.ValueType).Select(x => ValueDisplay(typeDef, Enum.Parse(typeDef.ValueType, x))));
            }

            return Constructor.NodeComponentList(
                Constructor.NodeComponentAutoCloner(Constructor.NodeField("Case").WithInput(typeDef).WithFlowOutput(), 0, (x) => $"Case {x + 1}"),
                defaultOutput
            );
        }

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

public async Task<IResult<EdgeFiles>> GetFiles(string name, string version)
        {
            var res2 = await GetGeneratedLink(name, version);
            if (res2.Success)
            {
                EdgeFiles edgeFiles = new EdgeFiles
                {
                    Version = version
                };

                if (res2.Value.Count > 0)
                {
                    edgeFiles.EdgeFile = new EdgeFile[res2.Value.Count];

                    for (int i = 0; i < res2.Value.Count; i++)
                    {
                        //if it's a full update == 2 underscores
                        //3 underscores == delta update

                        var splitted = res2.Value[i].FileId.Replace(".exe", "", StringComparison.InvariantCultureIgnoreCase).Split('_');
                        bool isDeltaUpdate = splitted.Length >= 4;

                        //var edgeName = splitted[0];
                        //var arch = splitted[1];
                        //var version = splitted[2];
                        //var deltaUpdate = splitted[3];

                        edgeFiles.EdgeFile[i] = new EdgeFile
                        {
                            FileName = res2.Value[i].FileId,
                            Sha1 = Convert.FromBase64String(res2.Value[i].Hashes.Sha1),
                            Sha256 = Convert.FromBase64String(res2.Value[i].Hashes.Sha256),
                            Size = res2.Value[i].SizeInBytes,
                            Url = res2.Value[i].Url,
                            EdgeFileUpdateType = isDeltaUpdate ? EdgeFileUpdateType.Delta : EdgeFileUpdateType.Full,
                            DeltaVersion = isDeltaUpdate ? splitted[3] : null,
                            Arch = Enum.Parse<Arch>(splitted[1], true)
                        };
                    }

                    return new Result<EdgeFiles>(true, edgeFiles);
                }
                else
                {
                    return new Result<EdgeFiles>(false, "Missing files", ResultType.Other);
                }
            }
            else
            {
                return new Result<EdgeFiles>(false, res2.Message, res2.ResultType);
            }
        }

19 View Source File : SqlConnectionExtensions.cs
License : MIT License
Project Creator : adospace

private static SqlDbType TryGetSqlDbTypeFromString(string typeName)
        {
            //ref https://docs.microsoft.com/en-us/dotnet/framework/data/adonet/sql-server-data-type-mappings
            if (typeName == "sql_variant")
                return SqlDbType.Variant;
            if (typeName == "smalldatetime")
                return SqlDbType.DateTime;
            if (typeName == "rowversion")
                return SqlDbType.Timestamp;
            if (typeName == "numeric")
                return SqlDbType.Decimal;
            if (typeName == "image")
                return SqlDbType.Binary;
            if (typeName == "binary")
                return SqlDbType.VarBinary;


            return (SqlDbType)Enum.Parse(typeof(SqlDbType), typeName, true);
        }

19 View Source File : SyntaxWalkerBase.cs
License : MIT License
Project Creator : adrianoc

private IEnumerable<string> ProcessDllImportAttribute(AttributeSyntax attribute, string methodVar)
        {
            var moduleName = attribute.ArgumentList?.Arguments.First().ToFullString();
            var existingModuleVar = Context.DefinitionVariables.GetVariable(moduleName, MemberKind.ModuleReference);
            
            var moduleVar = existingModuleVar.IsValid 
                ?  existingModuleVar.VariableName
                :  Context.Naming.SyntheticVariable("dllImportModule", ElementKind.LocalVariable); 

            var exps = new List<string>
            {
                $"{methodVar}.PInvokeInfo = new PInvokeInfo({ PInvokeAttributesFrom(attribute) }, { EntryPoint() }, {moduleVar});",
                $"{methodVar}.Body = null;",
                $"{methodVar}.ImplAttributes = {MethodImplAttributes()};",
            };

            if (!existingModuleVar.IsValid)
            {
                exps.InsertRange(0, new []
                {
                    $"var {moduleVar} = new ModuleReference({moduleName});",
                    $"replacedembly.MainModule.ModuleReferences.Add({moduleVar});",
                });
            }

            Context.DefinitionVariables.RegisterNonMethod("", moduleName, MemberKind.ModuleReference, moduleVar);
            
            return exps;
            
            string EntryPoint() => attribute?.ArgumentList?.Arguments.FirstOrDefault(arg => arg.NameEquals?.Name.Identifier.Text == "EntryPoint")?.Expression.ToString() ?? "\"\"";

            string MethodImplAttributes()
            {
                var preserveSig = Boolean.Parse(AttributePropertyOrDefaultValue(attribute, "PreserveSig", "true"));
                return preserveSig 
                    ? "MethodImplAttributes.PreserveSig | MethodImplAttributes.Managed" 
                    : "MethodImplAttributes.Managed";
            }

            string CallingConventionFrom(AttributeSyntax attr)
            {
                var callingConventionStr = attr.ArgumentList?.Arguments.FirstOrDefault(arg => arg.NameEquals?.Name.Identifier.Text == "CallingConvention")?.Expression.ToFullString() 
                                           ?? "Winapi";

                // ensures we use the enum member simple name; Parse() fails if we preplaced a qualified enum member
                var index = callingConventionStr.LastIndexOf('.');
                callingConventionStr = callingConventionStr.Substring(index + 1);
                
                return CallingConventionToCecil(Enum.Parse<CallingConvention>(callingConventionStr));
            }

            string CharSetFrom(AttributeSyntax attr)
            {
                var enumMemberName = AttributePropertyOrDefaultValue(attr, "CharSet", "None");

                // Only use the actual enum member name Parse() fails if we preplaced a qualified enum member
                var index = enumMemberName.LastIndexOf('.');
                enumMemberName = enumMemberName.Substring(index + 1);

                var charSet = Enum.Parse<CharSet>(enumMemberName);
                return charSet == CharSet.None ? string.Empty : $"PInvokeAttributes.CharSet{charSet}";
            }

            string SetLastErrorFrom(AttributeSyntax attr)
            {
                var setLastError = bool.Parse(AttributePropertyOrDefaultValue(attr, "SetLastError", "false"));
                return setLastError ? "PInvokeAttributes.SupportsLastError" : string.Empty;
            }

            string ExactSpellingFrom(AttributeSyntax attr)
            {
                var exactSpelling = bool.Parse(AttributePropertyOrDefaultValue(attr, "ExactSpelling", "false"));
                return exactSpelling ? "PInvokeAttributes.NoMangle" : string.Empty;
            }

            string BestFitMappingFrom(AttributeSyntax attr)
            {
                var bestFitMapping = bool.Parse(AttributePropertyOrDefaultValue(attr, "BestFitMapping", "true"));
                return bestFitMapping ? "PInvokeAttributes.BestFitEnabled" : "PInvokeAttributes.BestFitDisabled";
            }

            string ThrowOnUnmappableCharFrom(AttributeSyntax attr)
            {
                var bestFitMapping = bool.Parse(AttributePropertyOrDefaultValue(attr, "ThrowOnUnmappableChar", "false"));
                return bestFitMapping ? "PInvokeAttributes.ThrowOnUnmappableCharEnabled" : "PInvokeAttributes.ThrowOnUnmappableCharDisabled";
            }

            // For more information and default values see
            // https://docs.microsoft.com/en-us/dotnet/api/system.runtime.interopservices.dllimportattribute
            string PInvokeAttributesFrom(AttributeSyntax attr)
            {
                return CallingConventionFrom(attr)
                    .AppendModifier(CharSetFrom(attr))
                    .AppendModifier(SetLastErrorFrom(attr))
                    .AppendModifier(ExactSpellingFrom(attr))
                    .AppendModifier(BestFitMappingFrom(attr))
                    .AppendModifier(ThrowOnUnmappableCharFrom(attr));
            }

            string AttributePropertyOrDefaultValue(AttributeSyntax attr, string propertyName, string defaultValue)
            {
                return attr.ArgumentList?.Arguments.FirstOrDefault(arg => arg.NameEquals?.Name.Identifier.Text == propertyName)?.Expression.ToFullString() ?? defaultValue;
            }
        }

19 View Source File : IRCompiler.cs
License : GNU General Public License v3.0
Project Creator : Aekras1a

IRInstruction ReadInstr(Node node) {
			var instr = new IRInstruction(IROpCode.NOP);
			for (int i = 0; i < node.Count; i++) {
				var child = node[i];
				if (child.Id == (int)IRConstants.OP_CODE) {
					instr.OpCode = (IROpCode)Enum.Parse(typeof(IROpCode), ((Token)child[0]).Image);
				}
				else if (child.Id == (int)IRConstants.OPERAND) {
					if (instr.Operand1 == null)
						instr.Operand1 = ReadOperand(child);
					else
						instr.Operand2 = ReadOperand(child);
				}
			}
			if (instr.Operand1 is UnresolvedReference || instr.Operand2 is UnresolvedReference)
				references.Add(instr);
			return instr;
		}

19 View Source File : IRCompiler.cs
License : GNU General Public License v3.0
Project Creator : Aekras1a

void ReadType(Node node, ref ASTType type, ref TypeSig rawType) {
			for (int i = 0; i < node.Count; i++) {
				var child = node[i];
				if (child.Id == (int)IRConstants.ASTTYPE) {
					type = (ASTType)Enum.Parse(typeof(ASTType), ((Token)child).Image);
				}
				else if (child.Id == (int)IRConstants.RAW_TYPE) {
					var propertyName = ((Token)child[0]).Image;
					var property = typeof(ICorLibTypes).GetProperty(propertyName);
					rawType = (TypeSig)property.GetValue(module.CorLibTypes, null);
				}
			}
		}

19 View Source File : IRCompiler.cs
License : GNU General Public License v3.0
Project Creator : Aekras1a

IRRegister ReadRegister(Node node) {
			var type = ASTType.I4;
			TypeSig rawType = null;
			VMRegisters? reg = null;

			for (int i = 0; i < node.Count; i++) {
				var child = node[i];
				if (child.Id == (int)IRConstants.TYPE) {
					ReadType(child, ref type, ref rawType);
				}
				else if (child.Id == (int)IRConstants.REG) {
					var token = (Token)child;
					reg = (VMRegisters)Enum.Parse(typeof(VMRegisters), token.Image);
				}
			}
			Debug.replacedert(reg != null);
			return new IRRegister(reg.Value, type) {
				SourceVariable = rawType == null ? null : GetTypedVariable(type, rawType)
			};
		}

19 View Source File : HeckEventData.cs
License : MIT License
Project Creator : Aeroluna

private static HeckEventData ProcessCoroutineEvent(CustomEventData customEventData, IReadonlyBeatmapData beatmapData)
        {
            HeckEventData heckEventData = new HeckEventData();

            string? easingString = customEventData.data.Get<string>(EASING);
            heckEventData.Easing = Functions.easeLinear;
            if (easingString != null)
            {
                heckEventData.Easing = (Functions)Enum.Parse(typeof(Functions), easingString);
            }

            heckEventData.Duration = customEventData.data.Get<float?>(DURATION) ?? 0f;

            Track track = GetTrack(customEventData.data, beatmapData) ?? throw new InvalidOperationException("Track was not defined.");

            List<string> excludedStrings = new List<string> { TRACK, DURATION, EASING };
            IDictionary<string, Property> properties;
            switch (customEventData.type)
            {
                case ANIMATETRACK:
                    properties = track.Properties;
                    break;

                case replacedIGNPATHANIMATION:
                    properties = track.PathProperties;
                    break;

                default:
                    throw new InvalidOperationException("Custom event was not of correct type.");
            }

            foreach (KeyValuePair<string, object?> valuePair in customEventData.data)
            {
                if (!excludedStrings.Any(n => n == valuePair.Key))
                {
                    if (!properties.TryGetValue(valuePair.Key, out Property property))
                    {
                        Logger.Log($"Could not find property {valuePair.Key}!", IPA.Logging.Logger.Level.Error);
                        continue;
                    }

                    Dictionary<string, PointDefinition> pointDefinitions = (Dictionary<string, PointDefinition>)(((CustomBeatmapData)beatmapData).customData["pointDefinitions"] ?? throw new InvalidOperationException("Failed to retrieve point definitions."));
                    TryGetPointData(customEventData.data, valuePair.Key, out PointDefinition? pointData, pointDefinitions);

                    HeckEventData.CoroutineInfo coroutineInfo = new HeckEventData.CoroutineInfo(pointData, property);

                    heckEventData.CoroutineInfos.Add(coroutineInfo);
                }
            }

            return heckEventData;
        }

19 View Source File : EnumHelper.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

public static List<IEnumInfomation> GetEnumInfomation(Type type)
        {
            if (type == null)
            {
                return new List<IEnumInfomation>();
            }
            if (EnumInfomationMaps.ContainsKey(type))
            {
                return EnumInfomationMaps[type];
            }

            var enumFieldInfos = type.GetFields();
            var kvs = enumFieldInfos.Where(p => p.Name != "value__").Select(fieldInfo => (IEnumInfomation)new EnumInfomation
            {
                Caption = fieldInfo.GetDescription(),
                Value = Enum.Parse(type, fieldInfo.Name, true),
                LValue = Convert.ToInt64(Enum.Parse(type, fieldInfo.Name, true))
            }).ToList();

            EnumInfomationMaps.Add(type, kvs);

            return kvs;
        }

19 View Source File : EnumConverter.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value == null)
            {
                return default(TE);
            }
            string sValue = value.ToString().Trim();

            if (string.IsNullOrWhiteSpace(sValue) || sValue == "无")
                return default(TE);

            string[] sWords = sValue.Split(',', ' ', ';', '.', '\r', '\n', '\t');

            StringBuilder sb = new StringBuilder();
            foreach (var word in sWords.Where(p => !string.IsNullOrWhiteSpace(p)))
            {
                EnumInfomation<TE> ei = EnumValues.FirstOrDefault(p => p.Caption == word);
                if (ei == null)
                    continue;
                if (sb.Length > 0)
                {
                    sb.Append(" , ");
                }
                sb.Append(ei.Value);
            }
            try
            {
                return Enum.Parse(typeof(TE), sb.ToString(), false);
            }
            catch
            {
                return default(TE);
            }
        }

19 View Source File : EnumConverter.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value == null)
            {
                return default( TE );
            }
            long l = (long)value;
            if (l <= 0)
                return default( TE );

            StringBuilder sb = new StringBuilder();
            foreach (var ev in EnumValues)
            {
                if(( l & ev.LValue) != ev.LValue)
                    continue;
                if (sb.Length > 0)
                {
                    sb.Append(" , ");
                }
                sb.Append(ev.Value);
            }
            try
            {
                return Enum.Parse(typeof(TE), sb.ToString(), false);
            }
            catch
            {
                return default(TE);
            }
        }

19 View Source File : ConfigurationExtensions.cs
License : MIT License
Project Creator : Aiko-IT-Systems

private static void HydrateInstance(ref object config, ConfigSection section)
        {
            var props = config.GetType().GetProperties();

            foreach (var prop in props)
            {
                // Must have a set method for this to work, otherwise continue on
                if (prop.SetMethod == null)
                    continue;

                var entry = section.GetValue(prop.Name);
                object? value = null;

                if (typeof(string) == prop.PropertyType)
                {
                    // We do NOT want to override value if nothing was provided
                    if(!string.IsNullOrEmpty(entry))
                        prop.SetValue(config, entry);

                    continue;
                }

                // We need to address collections a bit differently
                // They can come in the form of    "root:section:name" with a string representation OR
                // "root:section:name:0"  <--- this is not detectable when checking the above path
                if (typeof(IEnumerable).IsreplacedignableFrom(prop.PropertyType))
                {
                    value = string.IsNullOrEmpty(section.GetValue(prop.Name))
                        ? section.Config
                            .GetSection(section.GetPath(prop.Name)).Get(prop.PropertyType)
                        : Newtonsoft.Json.JsonConvert.DeserializeObject(entry, prop.PropertyType);

                    if (value == null)
                        continue;

                    prop.SetValue(config, value);
                }

                // From this point onward we require the 'entry' value to have something useful
                if (string.IsNullOrEmpty(entry))
                    continue;

                try
                {
                    // Primitive types are simple to convert
                    if (prop.PropertyType.IsPrimitive)
                        value = Convert.ChangeType(entry, prop.PropertyType);
                    else
                    {
                        // The following types require a different approach
                        if (prop.PropertyType.IsEnum)
                            value = Enum.Parse(prop.PropertyType, entry);
                        else if (typeof(TimeSpan) == prop.PropertyType)
                            value = TimeSpan.Parse(entry);
                        else if (typeof(DateTime) == prop.PropertyType)
                            value = DateTime.Parse(entry);
                        else if (typeof(DateTimeOffset) == prop.PropertyType)
                            value = DateTimeOffset.Parse(entry);
                    }

                    // Update value within our config instance
                    prop.SetValue(config, value);
                }
                catch (Exception ex)
                {
                    Console.Error.WriteLine(
                        $"Unable to convert value of '{entry}' to type '{prop.PropertyType.Name}' for prop '{prop.Name}' in config '{config.GetType().Name}'\n\t\t{ex.Message}");
                }
            }
        }

19 View Source File : EnumType.cs
License : Apache License 2.0
Project Creator : ajuna-network

public void Create(byte[] byteArray)
        {
            Bytes = byteArray;
            Value = (T) System.Enum.Parse(typeof(T), byteArray[0].ToString(), true);

            //if (byteArray.Length < Size())
            //{
            //    var newByteArray = new byte[Size()];
            //    byteArray.CopyTo(newByteArray, 0);
            //    byteArray = newByteArray;
            //}

            //Bytes = byteArray;
            //Value = (T)System.Enum.Parse(typeof(T), BitConverter.ToUInt32(byteArray, 0).ToString(), true);
        }

19 View Source File : ExtEnumType.cs
License : Apache License 2.0
Project Creator : ajuna-network

public void Decode(byte[] byteArray, ref int p)
        {
            var start = p;
            var enumByte = byteArray[p];

            Value = (T0)System.Enum.Parse(typeof(T0), enumByte.ToString(), true);
            p += 1;

            Value2 = DecodeOneOf(enumByte, byteArray, ref p);

            _size = p - start;
        }

19 View Source File : DBEntryTheaterSpawnPoint.cs
License : GNU General Public License v3.0
Project Creator : akaAgar

internal bool Load(INIFile ini, string key)
        {
            string[] vals = ini.GetValueArray<string>("SpawnPoints", key, ',');
            UniqueID = key;

            if (vals.Length < 3) return false;

            try
            {
                Coordinates = new Coordinates(Toolbox.StringToDouble(vals[0]), Toolbox.StringToDouble(vals[1]));
                PointType = (SpawnPointType)Enum.Parse(typeof(SpawnPointType), vals[2], true);
            }
            catch (Exception)
            {
                return false;
            }

            return true;
        }

See More Examples