System.Enum.ToString()

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

4174 Examples 7

19 Source : GetInput.xaml.cs
with GNU General Public License v3.0
from 00000vish

private void textBox1_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
        {
            if (e.Key.ToString().Equals("Return"))
            {
                givenInput = true;
            }
        }

19 Source : GetInput.xaml.cs
with GNU General Public License v3.0
from 00000vish

private void PreplacedwordBox1_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
        {
            if (e.Key.ToString().Equals("Return"))
            {
                givenInput = true;
            }
        }

19 Source : steamChatWindow.xaml.cs
with GNU General Public License v3.0
from 00000vish

private void textbox1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key.ToString().Equals("Return"))
            {
                sendMessage();
                textbox1.Text = "";
            }
        }

19 Source : Log.cs
with MIT License
from 0ffffffffh

private static void Write(LogType type, string format, params object[] args)
        {
            ConsoleColor typeColor,origColor;
            ulong mask = (ulong)type;

            string log = string.Format(format, args);

            logFile.Write(type.ToString() + ": " + log);

            if ((logMask & mask) == mask)
            {
                typeColor = GetColorByLogType(type);

                lock (consLock)
                {
                    origColor = Console.ForegroundColor;
                    Console.ForegroundColor = typeColor;

                    Console.Write(string.Format("{0}: ", type.ToString()));

                    Console.ForegroundColor = origColor;

                    Console.WriteLine(log);
                }
            }
        }

19 Source : Logger.cs
with MIT License
from 0x0ade

public static void Log(LogLevel level, string tag, string str) {
            if (level < Level)
                return;

            TextWriter w = Writer;
            w.Write("(");
            w.Write(DateTime.Now);
            w.Write(LogCelesteNetTag ? ") [CelesteNet] [" : ") [");
            w.Write(level.ToString());
            w.Write("] [");
            w.Write(tag);
            w.Write("] ");
            w.WriteLine(str);
        }

19 Source : GmicPipeServer.cs
with GNU General Public License v3.0
from 0xC0000054

private string GetMaxLayerSize(InputMode inputMode)
        {
            int width = 0;
            int height = 0;

            switch (inputMode)
            {
                case InputMode.NoInput:
                case InputMode.AllHiddenLayers:
                case InputMode.AllHiddenLayersDescending:
                    break;
                case InputMode.ActiveLayer:
                case InputMode.ActiveAndBelow:
                    // The last layer in the list is always the layer the user has selected in Paint.NET,
                    // so it will be treated as the active layer.
                    // The clipboard layer (if present) will be placed above the active layer.
                    GmicLayer activeLayer = layers[layers.Count - 1];

                    width = activeLayer.Width;
                    height = activeLayer.Height;
                    break;

                case InputMode.AllLayers:
                case InputMode.ActiveAndAbove:
                case InputMode.AllVisibleLayers:
                case InputMode.AllVisibleLayersDescending:
                    foreach (GmicLayer layer in layers)
                    {
                        width = Math.Max(width, layer.Width);
                        height = Math.Max(height, layer.Height);
                    }
                    break;
                default:
                    throw new InvalidOperationException("Unsupported InputMode: " + inputMode.ToString());
            }

            return width.ToString(CultureInfo.InvariantCulture) + "," + height.ToString(CultureInfo.InvariantCulture);
        }

19 Source : GmicPipeServer.cs
with GNU General Public License v3.0
from 0xC0000054

private IReadOnlyList<GmicLayer> GetRequestedLayers(InputMode mode)
        {
            if (mode == InputMode.ActiveLayer ||
                mode == InputMode.ActiveAndBelow)
            {
                // The last layer in the list is always the layer the user has selected in Paint.NET,
                // so it will be treated as the active layer.
                // The clipboard layer (if present) will be placed above the active layer.

                return new GmicLayer[] { layers[layers.Count - 1] };
            }
            else if (mode == InputMode.AllVisibleLayersDescending)
            {
                List<GmicLayer> reversed = new List<GmicLayer>(layers.Count);

                for (int i = layers.Count - 1; i >= 0; i--)
                {
                    reversed.Add(layers[i]);
                }

                return reversed;
            }
            else
            {
                switch (mode)
                {
                    case InputMode.AllLayers:
                    case InputMode.ActiveAndAbove:
                    case InputMode.AllVisibleLayers:
                        return layers;
                    case InputMode.AllHiddenLayers:
                    case InputMode.AllHiddenLayersDescending:
                        return Array.Empty<GmicLayer>();
                    default:
                        throw new ArgumentException("The mode was not handled: " + mode.ToString());
                }
            }
        }

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

public static string ToDescription(this Enum value)
    {
        var type = value.GetType();
        var info = type.GetField(value.ToString());
        var key = type.FullName + info.Name;
        if (!DescriptionCache.TryGetValue(key, out string desc))
        {
            var attrs = info.GetCustomAttributes(typeof(DescriptionAttribute), true);
            if (attrs.Length < 1)
                desc = string.Empty;
            else
                desc = attrs[0] is DescriptionAttribute
                    descriptionAttribute
                    ? descriptionAttribute.Description
                    : value.ToString();

            DescriptionCache.TryAdd(key, desc);
        }

        return desc;
    }

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

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

        if (!enumType.IsEnum)
            return null;

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

        return Options2Collection(options);
    }

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

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

        if (layer.Core == null)
            return;

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

            descriptor.EnumDescriptors.Add(enumDescriptor);
        }
    }

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

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

        if (!enumType.IsEnum)
            return null;

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

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

                list = Options2Collection(options);

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

            return list;

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

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

            return list;

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

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

void DrawQuickStart()
    {
        GUILayout.BeginVertical();

        GUILayout.Label("Quick Start", EditorStyles.boldLabel);

        var entryCount = quickstartData.clientCount + 1;
        // Make sure we have enough entries
        var minEntryCount = Math.Max(entryCount, 2);
        while (minEntryCount > quickstartData.entries.Count())
            quickstartData.entries.Add(new QuickstartEntry());

        string str = "Starting Game - Server (Headless) & " + quickstartData.clientCount.ToString() + " clients";
        GUILayout.Label(str, EditorStyles.boldLabel);

        Color defaultGUIBackgrounColor = GUI.backgroundColor;
        // Quick start buttons
        GUILayout.BeginHorizontal();
        {
            GUI.backgroundColor = Color.green;
            if (GUILayout.Button("Start"))
            {
                for (int i = 0; i < entryCount; i++)
                {
                    if (quickstartData.entries[i].runInEditor)
                        continue;
                        //EditorLevelManager.StartGameInEditor();
                    else
                    {
                        RunBuild(quickstartData.entries[i].gameLoopMode);
                    }
                }
            }
            GUI.backgroundColor = defaultGUIBackgrounColor;

            GUI.backgroundColor = Color.red;
            if (GUILayout.Button("Stop All"))
            {
                StopAll();
            }
            GUI.backgroundColor = defaultGUIBackgrounColor;
        }
        GUILayout.EndHorizontal();

        // Settings
        EditorGUI.BeginChangeCheck();

        quickstartData.clientCount = EditorGUILayout.IntField("Clients", quickstartData.clientCount);

        quickstartData.editorRole = (EditorRole)EditorGUILayout.EnumPopup("Use Editor as", quickstartData.editorRole);

        quickstartData.entries[0].gameLoopMode = GameLoopMode.Server;
        quickstartData.entries[0].headless = quickstartData.headlessServer;

        quickstartData.entries[0].runInEditor = quickstartData.editorRole == EditorRole.Server;
        quickstartData.entries[1].runInEditor = quickstartData.editorRole == EditorRole.Client;

        for (var i = 1; i < entryCount; i++)
        {
            quickstartData.entries[i].gameLoopMode = GameLoopMode.Client;
            quickstartData.entries[i].headless = false;
        }

        // Draw entries
        GUILayout.Label("Started processes:");
        for (var i = 0; i < entryCount; i++)
        {
            var entry = quickstartData.entries[i];
            GUILayout.BeginVertical();
            {
                GUILayout.BeginHorizontal();
                {
                    GUILayout.Space(20);

                    GUILayout.Label("- Stand Alone Build", GUILayout.Width(130));

                    EditorGUILayout.SelectableLabel(entry.gameLoopMode.ToString(), EditorStyles.textField, GUILayout.Height(EditorGUIUtility.singleLineHeight));
                }
                GUILayout.EndHorizontal();
            }
            GUILayout.EndVertical();
        }

        GUILayout.EndVertical();
    }

19 Source : Program.cs
with MIT License
from 1iveowl

static async Task SendResponseAsync(IHttpRequestResponse request, HttpSender httpSender)
        {
            if (request.RequestType == RequestType.TCP)
            {
                var response = new HttpResponse
                {
                    StatusCode = (int)HttpStatusCode.OK,
                    ResponseReason = HttpStatusCode.OK.ToString(),
                    Headers = new Dictionary<string, string>
                    {
                        {"Date", DateTime.UtcNow.ToString("r")},
                        {"Content-Type", "text/html; charset=UTF-8" },
                    },
                    Body = new MemoryStream(Encoding.UTF8.GetBytes($"<html>\r\n<body>\r\n<h1>Hello, World! {DateTime.Now}</h1>\r\n</body>\r\n</html>"))
                };

                await httpSender.SendTcpResponseAsync(request, response).ConfigureAwait(false);
            }
        }

19 Source : TypeHelper.cs
with MIT License
from 279328316

internal static string GetModuleMark(Type type)
        {
            string moduleMark = type.ToString();

            switch (type.MemberType)
            {
                case MemberTypes.TypeInfo:
                    moduleMark = type.ToString();
                    break;
            }
            moduleMark = type.MemberType.ToString().Substring(0, 1) + ":" + moduleMark;
            return moduleMark;
        }

19 Source : UpdateHandle.cs
with GNU General Public License v3.0
from 2dust

private async void CheckUpdateAsync(string type)
        {
            try
            {
                Utils.SetSecurityProtocol();
                WebRequestHandler webRequestHandler = new WebRequestHandler
                {
                    AllowAutoRedirect = false
                };
                if (httpProxyTest() > 0)
                {
                    int httpPort = _config.GetLocalPort(Global.InboundHttp);
                    WebProxy webProxy = new WebProxy(Global.Loopback, httpPort);
                    webRequestHandler.Proxy = webProxy;
                }
                HttpClient httpClient = new HttpClient(webRequestHandler);

                string url;
                if (type == "v2fly")
                {
                    url = v2flyCoreLatestUrl;
                }
                else if (type == "xray")
                {
                    url = xrayCoreLatestUrl;
                }
                else if (type == "v2rayN")
                {
                    url = nLatestUrl;
                }
                else
                {
                    throw new ArgumentException("Type");
                }
                HttpResponseMessage response = await httpClient.GetAsync(url);
                if (response.StatusCode.ToString() == "Redirect")
                {
                    responseHandler(type, response.Headers.Location.ToString());
                }
                else
                {
                    Utils.SaveLog("StatusCode error: " + url);
                    return;
                }
            }
            catch (Exception ex)
            {
                Utils.SaveLog(ex.Message, ex);
                _updateFunc(false, ex.Message);
            }
        }

19 Source : HotKeys.cs
with MIT License
from 3RD-Dimension

public string KeyToString(Key key)
            {
                var ret = key.ToString();

                switch (key)
                {
                    //case Key.NumPad0:
                    //    ret = "0";
                    //    break;
                    //case Key.NumPad1:
                    //    ret = "1";
                    //    break;
                    //case Key.NumPad2:
                    //    ret = "2";
                    //    break;
                    //case Key.NumPad3:
                    //    ret = "3";
                    //    break;
                    //case Key.NumPad4:
                    //    ret = "4";
                    //    break;
                    //case Key.NumPad5:
                    //    ret = "5";
                    //    break;
                    //case Key.NumPad6:
                    //    ret = "6";
                    //    break;
                    //case Key.NumPad7:
                    //    ret = "7";
                    //    break;
                    //case Key.NumPad8:
                    //    ret = "8";
                    //    break;
                    //case Key.NumPad9:
                    //    ret = "9";
                    //    break;
                    //case Key.Down:
                    //    ret = "Down Arrow";
                    //    break;
                    //case Key.Up:
                    //    ret = "Up Arrow";
                    //    break;
                    //case Key.Right:
                    //    ret = "Right Arrow";
                    //    break;
                    //case Key.Left:
                    //    ret = "Left Arrow";
                    //    break;
                    case Key.Subtract:
                        ret = "-";
                        break;
                    case Key.Add:
                        ret = "+";
                        break;
                    case Key.Multiply:
                        ret = "*";
                        break;
                    case Key.Divide:
                        ret = "/";
                        break;
                    case Key.Decimal:
                        ret = ",";
                        break;
                    case Key.OemComma:
                        ret = ",";
                        break;
                    case Key.OemPeriod:
                        ret = ".";
                        break;
                    case Key.OemPipe:
                        ret = "|";
                        break;
                    case Key.Oem3:
                        ret = "`";
                        break;
                    case Key.Oem6:
                        ret = "]";
                        break;
                    case Key.OemOpenBrackets:
                        ret = "[";
                        break;
            }

                return ret;
            }

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

private static long ReadTimeSpanTicks(ProtoReader source, out DateTimeKind kind) {
            kind = DateTimeKind.Unspecified;
            switch (source.WireType)
            {
                case WireType.String:
                case WireType.StartGroup:
                    SubItemToken token = ProtoReader.StartSubItem(source);
                    int fieldNumber;
                    TimeSpanScale scale = TimeSpanScale.Days;
                    long value = 0;
                    while ((fieldNumber = source.ReadFieldHeader()) > 0)
                    {
                        switch (fieldNumber)
                        {
                            case FieldTimeSpanScale:
                                scale = (TimeSpanScale)source.ReadInt32();
                                break;
                            case FieldTimeSpanValue:
                                source.replacedert(WireType.SignedVariant);
                                value = source.ReadInt64();
                                break;
                            case FieldTimeSpanKind:
                                kind = (DateTimeKind)source.ReadInt32();
                                switch(kind)
                                {
                                    case DateTimeKind.Unspecified:
                                    case DateTimeKind.Utc:
                                    case DateTimeKind.Local:
                                        break; // fine
                                    default:
                                        throw new ProtoException("Invalid date/time kind: " + kind.ToString());
                                }
                                break;
                            default:
                                source.SkipField();
                                break;
                        }
                    }
                    ProtoReader.EndSubItem(token, source);
                    switch (scale)
                    {
                        case TimeSpanScale.Days:
                            return value * TimeSpan.TicksPerDay;
                        case TimeSpanScale.Hours:
                            return value * TimeSpan.TicksPerHour;
                        case TimeSpanScale.Minutes:
                            return value * TimeSpan.TicksPerMinute;
                        case TimeSpanScale.Seconds:
                            return value * TimeSpan.TicksPerSecond;
                        case TimeSpanScale.Milliseconds:
                            return value * TimeSpan.TicksPerMillisecond;
                        case TimeSpanScale.Ticks:
                            return value;
                        case TimeSpanScale.MinMax:
                            switch (value)
                            {
                                case 1: return long.MaxValue;
                                case -1: return long.MinValue;
                                default: throw new ProtoException("Unknown min/max value: " + value.ToString());
                            }
                        default:
                            throw new ProtoException("Unknown timescale: " + scale.ToString());
                    }
                case WireType.Fixed64:
                    return source.ReadInt64();
                default:
                    throw new ProtoException("Unexpected wire-type: " + source.WireType.ToString());
            }
        }

19 Source : TLV_002D.cs
with MIT License
from 499116344

public static string GetLocalIP()
        {
            var localIP = "192.168.1.2";
            try
            {
                var host = Dns.GetHostEntry(Dns.GetHostName());
                foreach (var ip in host.AddressList)
                {
                    if (ip.AddressFamily.ToString() == "InterNetwork")
                    {
                        localIP = ip.ToString();
                        break;
                    }
                }
            }
            catch (Exception)
            {
                localIP = "192.168.1.2";
            }

            return localIP;
        }

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

public static string ToDescription(this Enum value)
        {
            var type = value.GetType();
            var member = type.GetMember(value.ToString()).FirstOrDefault();
            return member != null ? member.ToDescription() : value.ToString();
        }

19 Source : FlipActions.cs
with MIT License
from 8bitbytes

private Action CreateAction(FlipDirections direction)
        {
            return new Action(direction.ToString(),$"flip {getFlipDirectionsString(direction)}",Action.ActionTypes.Control,Client);
        }

19 Source : EnumMethods.cs
with MIT License
from 8T4

[ExcludeFromCodeCoverage]
        public static string GetDescription(this Enum genericEnum)
        {
            var genericEnumType = genericEnum.GetType();
            var memberInfo = genericEnumType.GetMember(genericEnum.ToString());

            if (memberInfo.Length <= 0)
            {
                return genericEnum.ToString();
            }

            var attribs = memberInfo[0].GetCustomAttributes(typeof(System.ComponentModel.DescriptionAttribute), false);
            
            return attribs.Any() 
                ? ((System.ComponentModel.DescriptionAttribute)attribs.ElementAt(0)).Description 
                : genericEnum.ToString();
        }

19 Source : FlyActions.cs
with MIT License
from 8bitbytes

private Action CreateAction(FlyDirections direction, int distance)
        {
            return new Action(direction.ToString(), $"{direction.ToString().ToLower()} {distance}",Action.ActionTypes.Control, Client);
        }

19 Source : EnumType.cs
with Apache License 2.0
from 91270

public static string GetEnumText(this Enum obj)
        {
            Type type = obj.GetType();
            FieldInfo field = type.GetField(obj.ToString());
            TextAttribute attribute = (TextAttribute)field.GetCustomAttribute(typeof(TextAttribute));
            return attribute.Value;
        }

19 Source : RotationActions.cs
with MIT License
from 8bitbytes

private Action CreateAction(Rotations direction, int degrees)
        {
            return new Action(direction.ToString(), $"{getRotationString(direction)} {degrees}",Action.ActionTypes.Control, Client);
        }

19 Source : Mana.cs
with GNU General Public License v3.0
from a2659802

public void UpdateRequire()
            {
                if (require != null)
                {
                    StringBuilder sb = new StringBuilder();
                    foreach (var kv in require)
                    {
                        string color = "<#ffffff>";
                        switch (kv.Key)
                        {
                            case ManaType.U:
                                color = "<#67c1f5>";
                                break;
                            case ManaType.R:
                                color = "<#f85555>";
                                break;
                            case ManaType.B:
                                color = "<#848484>";
                                break;
                            case ManaType.G:
                                color = "<#25b569>";
                                break;
                            case ManaType.W:
                                color = "<#fcfcc1>";
                                break;
                            case ManaType.C:
                                color = "<#c0c0c0>";
                                break;
                        }
                        sb.Append(color);
                        sb.Append(kv.Key.ToString()[0], kv.Value);
                        sb.Append("</color>");
                    }
                    UpdateDialogue(sb.ToString());
                }
            }

19 Source : Brain.cs
with Apache License 2.0
from A7ocin

public void UpdateCoreBrains()
    {

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

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

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

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

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

        coreBrain.SetBrain(this);
    }

19 Source : VxSelectItem.cs
with MIT License
from Aaltuj

public static VxSelecreplacedem ToSelecreplacedem(Enum value)
        {
            var foundAttr = value.GetAttribute<DisplayAttribute>();
            if (foundAttr != null)
            {
                return new VxSelecreplacedem(foundAttr, value);
            }
            else
            {
                return new VxSelecreplacedem() { Label = value.ToString() };
            }
        }

19 Source : VxHelpers.cs
with MIT License
from Aaltuj

public static T GetAttribute<T>(this Enum value) where T : Attribute
        {
            var type = value.GetType();
            var memberInfo = type.GetMember(value.ToString());
            var attributes = memberInfo[0].GetCustomAttributes(typeof(T), false);
            return attributes.Length > 0
              ? (T)attributes[0]
              : null;
        }

19 Source : AttackThingState.cs
with Apache License 2.0
from AantCoder

public override string ToString()
        {
            return $"(hostId={HostThingID}, Pos=({Position.x},{Position.z}), HitP={HitPoints}, Cnt={StackCount} {DownState.ToString()})";
        }

19 Source : OvrWarpDX11Test.cs
with MIT License
from ab4d

protected void LogCallback(IntPtr userData, LogLevel level, string message)
        {
            string formattedMessage = string.Format("[{0}] {1}", level.ToString(), message);
            System.Diagnostics.Trace.WriteLine(formattedMessage);
        }

19 Source : CaretNavigationCommandHandler.cs
with MIT License
from Abdesol

internal static TextViewPosition GetNewCaretPosition(TextView textView, TextViewPosition caretPosition, CaretMovementType direction, bool enableVirtualSpace, ref double desiredXPos)
		{
			switch (direction) {
				case CaretMovementType.None:
					return caretPosition;
				case CaretMovementType.DoreplacedentStart:
					desiredXPos = double.NaN;
					return new TextViewPosition(0, 0);
				case CaretMovementType.DoreplacedentEnd:
					desiredXPos = double.NaN;
					return new TextViewPosition(textView.Doreplacedent.GetLocation(textView.Doreplacedent.TextLength));
			}
			DoreplacedentLine caretLine = textView.Doreplacedent.GetLineByNumber(caretPosition.Line);
			VisualLine visualLine = textView.GetOrConstructVisualLine(caretLine);
			TextLine textLine = visualLine.GetTextLine(caretPosition.VisualColumn, caretPosition.IsAtEndOfLine);
			switch (direction) {
				case CaretMovementType.CharLeft:
					desiredXPos = double.NaN;
					// do not move caret to previous line in virtual space
					if (caretPosition.VisualColumn == 0 && enableVirtualSpace)
						return caretPosition;
					return GetPrevCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.Normal, enableVirtualSpace);
				case CaretMovementType.Backspace:
					desiredXPos = double.NaN;
					return GetPrevCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.EveryCodepoint, enableVirtualSpace);
				case CaretMovementType.CharRight:
					desiredXPos = double.NaN;
					return GetNextCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.Normal, enableVirtualSpace);
				case CaretMovementType.WordLeft:
					desiredXPos = double.NaN;
					return GetPrevCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.WordStart, enableVirtualSpace);
				case CaretMovementType.WordRight:
					desiredXPos = double.NaN;
					return GetNextCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.WordStart, enableVirtualSpace);
				case CaretMovementType.LineUp:
				case CaretMovementType.LineDown:
				case CaretMovementType.PageUp:
				case CaretMovementType.PageDown:
					return GetUpDownCaretPosition(textView, caretPosition, direction, visualLine, textLine, enableVirtualSpace, ref desiredXPos);
				case CaretMovementType.LineStart:
					desiredXPos = double.NaN;
					return GetStartOfLineCaretPosition(caretPosition.VisualColumn, visualLine, textLine, enableVirtualSpace);
				case CaretMovementType.LineEnd:
					desiredXPos = double.NaN;
					return GetEndOfLineCaretPosition(visualLine, textLine);
				default:
					throw new NotSupportedException(direction.ToString());
			}
		}

19 Source : CaretNavigationCommandHandler.cs
with MIT License
from Abdesol

static TextViewPosition GetUpDownCaretPosition(TextView textView, TextViewPosition caretPosition, CaretMovementType direction, VisualLine visualLine, TextLine textLine, bool enableVirtualSpace, ref double xPos)
		{
			// moving up/down happens using the desired visual X position
			if (double.IsNaN(xPos))
				xPos = visualLine.GetTextLineVisualXPosition(textLine, caretPosition.VisualColumn);
			// now find the TextLine+VisualLine where the caret will end up in
			VisualLine targetVisualLine = visualLine;
			TextLine targetLine;
			int textLineIndex = visualLine.TextLines.IndexOf(textLine);
			switch (direction) {
				case CaretMovementType.LineUp: {
					// Move up: move to the previous TextLine in the same visual line
					// or move to the last TextLine of the previous visual line
					int prevLineNumber = visualLine.FirstDoreplacedentLine.LineNumber - 1;
					if (textLineIndex > 0) {
						targetLine = visualLine.TextLines[textLineIndex - 1];
					} else if (prevLineNumber >= 1) {
						DoreplacedentLine prevLine = textView.Doreplacedent.GetLineByNumber(prevLineNumber);
						targetVisualLine = textView.GetOrConstructVisualLine(prevLine);
						targetLine = targetVisualLine.TextLines[targetVisualLine.TextLines.Count - 1];
					} else {
						targetLine = null;
					}
					break;
				}
				case CaretMovementType.LineDown: {
					// Move down: move to the next TextLine in the same visual line
					// or move to the first TextLine of the next visual line
					int nextLineNumber = visualLine.LastDoreplacedentLine.LineNumber + 1;
					if (textLineIndex < visualLine.TextLines.Count - 1) {
						targetLine = visualLine.TextLines[textLineIndex + 1];
					} else if (nextLineNumber <= textView.Doreplacedent.LineCount) {
						DoreplacedentLine nextLine = textView.Doreplacedent.GetLineByNumber(nextLineNumber);
						targetVisualLine = textView.GetOrConstructVisualLine(nextLine);
						targetLine = targetVisualLine.TextLines[0];
					} else {
						targetLine = null;
					}
					break;
				}
				case CaretMovementType.PageUp:
				case CaretMovementType.PageDown: {
					// Page up/down: find the target line using its visual position
					double yPos = visualLine.GetTextLineVisualYPosition(textLine, VisualYPosition.LineMiddle);
					if (direction == CaretMovementType.PageUp)
						yPos -= textView.RenderSize.Height;
					else
						yPos += textView.RenderSize.Height;
					DoreplacedentLine newLine = textView.GetDoreplacedentLineByVisualTop(yPos);
					targetVisualLine = textView.GetOrConstructVisualLine(newLine);
					targetLine = targetVisualLine.GetTextLineByVisualYPosition(yPos);
					break;
				}
				default:
					throw new NotSupportedException(direction.ToString());
			}
			if (targetLine != null) {
				double yPos = targetVisualLine.GetTextLineVisualYPosition(targetLine, VisualYPosition.LineMiddle);
				int newVisualColumn = targetVisualLine.GetVisualColumn(new Point(xPos, yPos), enableVirtualSpace);

				// prevent wrapping to the next line; TODO: could 'IsAtEnd' help here?
				int targetLineStartCol = targetVisualLine.GetTextLineVisualStartColumn(targetLine);
				if (newVisualColumn >= targetLineStartCol + targetLine.Length) {
					if (newVisualColumn <= targetVisualLine.VisualLength)
						newVisualColumn = targetLineStartCol + targetLine.Length - 1;
				}
				return targetVisualLine.GetTextViewPosition(newVisualColumn);
			} else {
				return caretPosition;
			}
		}

19 Source : SimNetwork.cs
with MIT License
from abdullin

public string BodyString() {
            var body = Payload == null ? "" : Payload.ToString();
            if (Flag != SimFlag.None) {
                body += $" {Flag.ToString().ToUpperInvariant()}";
            }

            return body.Trim();
        }

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

public override string ToString()
        {
            string s = "";

            s += bindingType.ToString();

            switch (bindingType)
            {
                case KeyType.Key:
                    s += ": " + ((KeyCode)code).ToString();
                    break;
                case KeyType.Mouse:
                    s += ": " + ((MouseButton)code).ToString();
                    break;
            }
            return s;
        }

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

public void ValidateTextures(ovrAvatarPBSMaterialState[] materialStates)
    {
        var props = LocalAvatarConfig.ComponentMaterialProperties;

        int[] heights = new int[(int)TextureType.Count];
        TextureFormat[] formats = new TextureFormat[(int)TextureType.Count];

        for (var propIndex = 0; propIndex < props.Length; propIndex++)
        {
            for (var index = 0; index < props[propIndex].Textures.Length; index++)
            {
                if (props[propIndex].Textures[index] == null)
                {
                    throw new System.Exception(
                        props[propIndex].TypeIndex.ToString()
                        + "Invalid: "
                        + ((TextureType)index).ToString());
                }

                heights[index] = props[propIndex].Textures[index].height;
                formats[index] = props[propIndex].Textures[index].format;
            }
        }

        for (int textureIndex = 0; textureIndex < (int)TextureType.Count; textureIndex++)
        {
            for (var propIndex = 1; propIndex < props.Length; propIndex++)
            {
                if (props[propIndex - 1].Textures[textureIndex].height
                    != props[propIndex].Textures[textureIndex].height)
                {
                    throw new System.Exception(
                        props[propIndex].TypeIndex.ToString()
                        + " Mismatching Resolutions: "
                        + ((TextureType)textureIndex).ToString()
                        + " "
                        + props[propIndex - 1].Textures[textureIndex].height
                        + " (ID: "
                        + GetTextureIDForType(materialStates[propIndex - 1], (TextureType)textureIndex)
                        + ") vs "
                        + props[propIndex].Textures[textureIndex].height
                        + " (ID: "
                        + GetTextureIDForType(materialStates[propIndex], (TextureType)textureIndex)
                        + ") Ensure you are using ASTC texture compression on Android or turn off CombineMeshes");
                }

                if (props[propIndex - 1].Textures[textureIndex].format
                    != props[propIndex].Textures[textureIndex].format)
                {
                    throw new System.Exception(
                        props[propIndex].TypeIndex.ToString()
                        + " Mismatching Formats: "
                        + ((TextureType)textureIndex).ToString()
                        + " "
                        + props[propIndex - 1].Textures[textureIndex].format
                        + " (ID: "
                        + GetTextureIDForType(materialStates[propIndex - 1], (TextureType)textureIndex)
                        + ") vs "
                        + props[propIndex].Textures[textureIndex].format
                        + " (ID: "
                        + GetTextureIDForType(materialStates[propIndex], (TextureType)textureIndex)
                        + ") Ensure you are using ASTC texture compression on Android or turn off CombineMeshes");
                }
            }
        }
    }

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

void GenerateTexture(Cubemap cubemap, string pathName)
	{
		// Encode the texture and save it to disk
		pathName = pathName.Replace(".cubemap", (textureFormat == TexFormat.PNG) ? ".png" : ".jpg" ).ToLower();
		pathName = pathName.Replace( cubeMapFolder.ToLower(), "" );
		string format = textureFormat.ToString();
		string fullPath = EditorUtility.SaveFilePanel( string.Format( "Save Cubemap Screenshot as {0}", format ), "", pathName, format.ToLower() );
		if ( !string.IsNullOrEmpty( fullPath ) )
		{
			Debug.Log( "Saving: " + fullPath );
			OVRCubemapCapture.SaveCubemapCapture(cubemap, fullPath);
		}
	}

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

virtual protected void InitializeBones(OVRPlugin.Skeleton skeleton)
	{
		_bones = new List<OVRBone>(new OVRBone[skeleton.NumBones]);
		Bones = _bones.AsReadOnly();

		if (!_bonesGO)
		{
			_bonesGO = new GameObject("Bones");
			_bonesGO.transform.SetParent(transform, false);
			_bonesGO.transform.localPosition = Vector3.zero;
			_bonesGO.transform.localRotation = Quaternion.idenreplacedy;
		}

		// pre-populate bones list before attempting to apply bone hierarchy
		for (int i = 0; i < skeleton.NumBones; ++i)
		{
			BoneId id = (OVRSkeleton.BoneId)skeleton.Bones[i].Id;
			short parentIdx = skeleton.Bones[i].ParentBoneIndex;
			Vector3 pos = skeleton.Bones[i].Pose.Position.FromFlippedXVector3f();
			Quaternion rot = skeleton.Bones[i].Pose.Orientation.FromFlippedXQuatf();

			var boneGO = new GameObject(id.ToString());
			boneGO.transform.localPosition = pos;
			boneGO.transform.localRotation = rot;
			_bones[i] = new OVRBone(id, parentIdx, boneGO.transform);
		}

		for (int i = 0; i < skeleton.NumBones; ++i)
		{
			if (((OVRPlugin.BoneId)skeleton.Bones[i].ParentBoneIndex) == OVRPlugin.BoneId.Invalid)
			{
				_bones[i].Transform.SetParent(_bonesGO.transform, false);
			}
			else
			{
				_bones[i].Transform.SetParent(_bones[_bones[i].ParentBoneIndex].Transform, false);
			}
		}
	}

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

private void InitializeBindPose(OVRPlugin.Skeleton skeleton)
	{
		_bindPoses = new List<OVRBone>(new OVRBone[skeleton.NumBones]);
		BindPoses = _bindPoses.AsReadOnly();

		if (!_bindPosesGO)
		{
			_bindPosesGO = new GameObject("BindPoses");
			_bindPosesGO.transform.SetParent(transform, false);
			_bindPosesGO.transform.localPosition = Vector3.zero;
			_bindPosesGO.transform.localRotation = Quaternion.idenreplacedy;
		}

		for (int i = 0; i < skeleton.NumBones; ++i)
		{
			BoneId id = (OVRSkeleton.BoneId)skeleton.Bones[i].Id;
			short parentIdx = skeleton.Bones[i].ParentBoneIndex;
			var bindPoseGO = new GameObject(id.ToString());
			OVRBone bone = _bones[i];

			if (bone.Transform != null)
			{
				bindPoseGO.transform.localPosition = bone.Transform.localPosition;
				bindPoseGO.transform.localRotation = bone.Transform.localRotation;
			}

			_bindPoses[i] = new OVRBone(id, parentIdx, bindPoseGO.transform);
		}

		for (int i = 0; i < skeleton.NumBones; ++i)
		{
			if (((OVRPlugin.BoneId)skeleton.Bones[i].ParentBoneIndex) == OVRPlugin.BoneId.Invalid)
			{
				_bindPoses[i].Transform.SetParent(_bindPosesGO.transform, false);
			}
			else
			{
				_bindPoses[i].Transform.SetParent(_bindPoses[_bones[i].ParentBoneIndex].Transform, false);
			}
		}
	}

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

private void InitializeCapsules(OVRPlugin.Skeleton skeleton)
	{
		if (_enablePhysicsCapsules)
		{
			_capsules = new List<OVRBoneCapsule>(new OVRBoneCapsule[skeleton.NumBoneCapsules]);
			Capsules = _capsules.AsReadOnly();

			if (!_capsulesGO)
			{
				_capsulesGO = new GameObject("Capsules");
				_capsulesGO.transform.SetParent(transform, false);
				_capsulesGO.transform.localPosition = Vector3.zero;
				_capsulesGO.transform.localRotation = Quaternion.idenreplacedy;
			}

			_capsules = new List<OVRBoneCapsule>(new OVRBoneCapsule[skeleton.NumBoneCapsules]);
			Capsules = _capsules.AsReadOnly();

			for (int i = 0; i < skeleton.NumBoneCapsules; ++i)
			{
				var capsule = skeleton.BoneCapsules[i];
				Transform bone = Bones[capsule.BoneIndex].Transform;

				var capsuleRigidBodyGO = new GameObject((_bones[capsule.BoneIndex].Id).ToString() + "_CapsuleRigidBody");
				capsuleRigidBodyGO.transform.SetParent(_capsulesGO.transform, false);
				capsuleRigidBodyGO.transform.position = bone.position;
				capsuleRigidBodyGO.transform.rotation = bone.rotation;

				var capsuleRigidBody = capsuleRigidBodyGO.AddComponent<Rigidbody>();
				capsuleRigidBody.mreplaced = 1.0f;
				capsuleRigidBody.isKinematic = true;
				capsuleRigidBody.useGravity = false;
				capsuleRigidBody.collisionDetectionMode = CollisionDetectionMode.ContinuousSpeculative;

				var capsuleColliderGO = new GameObject((_bones[capsule.BoneIndex].Id).ToString() + "_CapsuleCollider");
				capsuleColliderGO.transform.SetParent(capsuleRigidBodyGO.transform, false);
				var capsuleCollider = capsuleColliderGO.AddComponent<CapsuleCollider>();
				var p0 = capsule.Points[0].FromFlippedXVector3f();
				var p1 = capsule.Points[1].FromFlippedXVector3f();
				var delta = p1 - p0;
				var mag = delta.magnitude;
				var rot = Quaternion.FromToRotation(Vector3.right, delta);
				capsuleCollider.radius = capsule.Radius;
				capsuleCollider.height = mag + capsule.Radius * 2.0f;
				capsuleCollider.isTrigger = false;
				capsuleCollider.direction = 0;
				capsuleColliderGO.transform.localPosition = p0;
				capsuleColliderGO.transform.localRotation = rot;
				capsuleCollider.center = Vector3.right * mag * 0.5f;

				_capsules[i] = new OVRBoneCapsule(capsule.BoneIndex, capsuleRigidBody, capsuleCollider);
			}
		}
	}

19 Source : EnumDescriptionConverter.cs
with MIT License
from ABTSoftware

public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            Enum e = value as Enum;
            if (e == null) return null;

            var type = e.GetType();
            var memInfo = type.GetMember(e.ToString());
            var attributes = memInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), false);
            var description = ((DescriptionAttribute)attributes[0]).Description;
            return description;
        }

19 Source : DataManager.cs
with MIT License
from ABTSoftware

public XyDataSeries<double> AggregateByCategory(Category category)
        {
            var dataSeries = new XyDataSeries<double> { SeriesName = category.ToString() };

            if (category == Category.Meat)
            {
                for (int i = 0; i < DataSeriesPork.Count; i++)
                {
                    dataSeries.Append(DataSeriesPork.XValues[i], 
                        DataSeriesPork.YValues[i] + DataSeriesVeal.YValues[i]);
                }
            }
            else if (category == Category.Vegetables)
            {
                for (int i = 0; i < DataSeriesTomato.Count; i++)
                {
                    dataSeries.Append(DataSeriesTomato.XValues[i],
                        DataSeriesTomato.YValues[i] + DataSeriesCureplacedber.YValues[i] + DataSeriesPepper.YValues[i]);
                }
            }
            return dataSeries;
        }

19 Source : TestParameters.cs
with MIT License
from ABTSoftware

public override string ToString()
        {
			return string.Format("{0} pts, AA={1}, StrokeThickness={2}, Resampling={3}, Distr={4}, TestRunner={5}", PointCount, AntiAliasing ? "On" : "Off", StrokeThickness, SamplingMode, DataDistribution,TestRunner.ToString());
        }

19 Source : Print.cs
with MIT License
from Accelerider

private static void WriteToConsole(string message, OutType outType = OutType.Info)
        {
            var backupBackground = Console.BackgroundColor;
            var backupForeground = Console.ForegroundColor;

            Console.BackgroundColor = OutColors[outType];
            Console.ForegroundColor = ConsoleColor.Gray;
            Console.Write($"[{outType.ToString().ToUpper()}]");
            Console.BackgroundColor = backupBackground;

            Console.ForegroundColor = OutColors[outType];
            var spaces = Enumerable.Repeat(" ", 8 - outType.ToString().Length).Aggregate((acc, item) => acc + item);
            Console.WriteLine($"{spaces}{message}");
            Console.ForegroundColor = backupForeground;
        }

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

public static string GetDescription(this PropertyAttribute prop)
        {
            var description = prop.GetAttributeOfType<DescriptionAttribute>();
            return description?.Description ?? prop.ToString();
        }

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

public static string GetDescription(this PropertyAttribute2nd prop)
        {
            var description = prop.GetAttributeOfType<DescriptionAttribute>();
            return description?.Description ?? prop.ToString();
        }

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

public static string ToSentence(this PropertyAttribute2nd attribute2nd)
        {
            return new string(attribute2nd.ToString().Replace("Max", "Maximum").ToCharArray().SelectMany((c, i) => i > 0 && char.IsUpper(c) ? new char[] { ' ', c } : new char[] { c }).ToArray());
        }

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

public static string GetDescription(this PropertyBool prop)
        {
            var description = prop.GetAttributeOfType<DescriptionAttribute>();
            return description?.Description ?? prop.ToString();
        }

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

public static string GetDescription(this PropertyDataId prop)
        {
            var description = prop.GetAttributeOfType<DescriptionAttribute>();
            return description?.Description ?? prop.ToString();
        }

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

public static string GetDescription(this PropertyFloat prop)
        {
            var description = prop.GetAttributeOfType<DescriptionAttribute>();
            return description?.Description ?? prop.ToString();
        }

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

public static string GetDescription(this PropertyInstanceId prop)
        {
            var description = prop.GetAttributeOfType<DescriptionAttribute>();
            return description?.Description ?? prop.ToString();
        }

See More Examples