string.ToCharArray()

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

3169 Examples 7

19 View Source File : StringHelper.cs
License : MIT License
Project Creator : 0x1000000

public static string FirstToLower(this string source)
        {
            if (string.IsNullOrEmpty(source) || char.IsLower(source[0])) 
            {
                return source;
            }

            char[] result = source.ToCharArray();
            result[0] = char.ToLower(result[0]);
            return new string(result);
        }

19 View Source File : DialogueManagerController.cs
License : MIT License
Project Creator : 0xbustos

private string ParseSentence( string sentence )
        {
            string parsedSentence = "";
            bool normalSentence = true;
            foreach (char letter in sentence.ToCharArray())
            {
                if (letter == '[')
                {
                    normalSentence = false;
                }

                if (letter == ']')
                {
                    normalSentence = true;
                }

                if (normalSentence)
                {
                    if (letter != ']')
                    {
                        parsedSentence += letter;
                    }
                }
            }

            return parsedSentence;
        }

19 View Source File : StringUtils.cs
License : Apache License 2.0
Project Creator : 0xFireball

public static string SecureRandomString(int maxSize)
        {
            var chars = new char[62];
            chars =
            "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890".ToCharArray();
            var data = new byte[1];
            using (var prng = RandomNumberGenerator.Create())
            {
                prng.GetBytes(data);
                data = new byte[maxSize];
                prng.GetBytes(data);
            }
            var result = new StringBuilder(maxSize);
            foreach (var b in data)
            {
                result.Append(chars[b % (chars.Length)]);
            }
            return result.ToString();
        }

19 View Source File : Dumper.cs
License : MIT License
Project Creator : 13xforever

public void DetectDisc(string inDir = "", Func<Dumper, string> outputDirFormatter = null)
        {
            outputDirFormatter ??= d => $"[{d.ProductCode}] {d.replacedle}";
            string discSfbPath = null;
            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                var drives = DriveInfo.GetDrives().Where(d => d.DriveType == DriveType.CDRom && d.IsReady);
                if (string.IsNullOrEmpty(inDir))
                {
                    foreach (var drive in drives)
                    {
                        discSfbPath = Path.Combine(drive.Name, "PS3_DISC.SFB");
                        if (!File.Exists(discSfbPath))
                            continue;

                        input = drive.Name;
                        Drive = drive.Name[0];
                        break;
                    }
                }
                else
                {
                    discSfbPath = Path.Combine(inDir, "PS3_DISC.SFB");
                    if (File.Exists(discSfbPath))
                    {
                        input = Path.GetPathRoot(discSfbPath);
                        Drive = discSfbPath[0];
                    }
                }
            }
            else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
            {
                if (string.IsNullOrEmpty(inDir))
                    inDir = "/media";
                discSfbPath = IOEx.GetFilepaths(inDir, "PS3_DISC.SFB", 2).FirstOrDefault();
                if (!string.IsNullOrEmpty(discSfbPath))
                    input = Path.GetDirectoryName(discSfbPath);
            }
            else
                throw new NotImplementedException("Current OS is not supported");

            if (string.IsNullOrEmpty(input) || string.IsNullOrEmpty(discSfbPath))
                throw new DriveNotFoundException("No valid PS3 disc was detected. Disc must be detected and mounted.");

            Log.Info("Selected disc: " + input);
            discSfbData = File.ReadAllBytes(discSfbPath);
            var replacedleId = CheckDiscSfb(discSfbData);
            var paramSfoPath = Path.Combine(input, "PS3_GAME", "PARAM.SFO");
            if (!File.Exists(paramSfoPath))
                throw new InvalidOperationException($"Specified folder is not a valid PS3 disc root (param.sfo is missing): {input}");

            using (var stream = File.Open(paramSfoPath, FileMode.Open, FileAccess.Read, FileShare.Read))
                ParamSfo = ParamSfo.ReadFrom(stream);
            CheckParamSfo(ParamSfo);
            if (replacedleId != ProductCode)
                Log.Warn($"Product codes in ps3_disc.sfb ({replacedleId}) and in param.sfo ({ProductCode}) do not match");

            // todo: maybe use discutils instead to read TOC as one block
            var files = IOEx.GetFilepaths(input, "*", SearchOption.AllDirectories);
            DiscFilenames = new List<string>();
            var totalFilesize = 0L;
            var rootLength = input.Length;
            foreach (var f in files)
            {
                try { totalFilesize += new FileInfo(f).Length; } catch { }
                DiscFilenames.Add(f.Substring(rootLength));
            }
            TotalFileSize = totalFilesize;
            TotalFileCount = DiscFilenames.Count;

            OutputDir = new string(outputDirFormatter(this).ToCharArray().Where(c => !InvalidChars.Contains(c)).ToArray());
            Log.Debug($"Output: {OutputDir}");
        }

19 View Source File : Program.cs
License : MIT License
Project Creator : 2401dem

public static int Denoise()
        {
            if (_is_folder)
            {
                if (Directory.Exists(_input_path) || Directory.Exists(_input_path.Substring(0, _input_path.LastIndexOf('\\') > 0 ? _input_path.LastIndexOf('\\') : 0)))
                {
                    if (Directory.Exists(_output_path) || Directory.Exists(_output_path.Substring(0, _output_path.LastIndexOf('\\') > 0 ? _output_path.LastIndexOf('\\') : 0)))
                    {
                        var file_paths = Directory.GetFiles(_input_path, "*.*", SearchOption.TopDirectoryOnly);
                        List<string> input_file_paths = new List<string>();
                        List<string> output_file_paths = new List<string>();
                        foreach (string file_path in file_paths)
                        {
                            Regex regex = new Regex(".\\.(bmp|jpg|png|tif|exr)$", RegexOptions.IgnoreCase);
                            if (regex.IsMatch(file_path))
                            {
                                input_file_paths.Add(file_path);
                                output_file_paths.Add(_output_path + "\\out_" + file_path.Substring(file_path.LastIndexOf('\\') + 1));
                                Console.WriteLine(file_path);
                            }
                        }
                        int width = _getWidth(input_file_paths[0].ToCharArray());
                        int height = _getHeight(input_file_paths[0].ToCharArray());

                        if (width == -1 || height == -1)
                        {
                            MessageBox.Show("Picture Format Error!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            Program.form1.unlockButton();
                            return -1;
                        }
                        //Bitmap pBuffer = new Bitmap(input_file_paths[0], false);
                        IntPtr tmpptr = new IntPtr();

                        _jobStart(width, height, _blend);
                        for (int i = 0; i < input_file_paths.Count; ++i)
                        {
                            Program.form1.SetProgress((float)i / (float)input_file_paths.Count);
                            if (File.Exists(output_file_paths[i]))
                                continue;
                            //IntPtr tmpptr = 
                            tmpptr = _denoiseImplement(input_file_paths[i].ToCharArray(), output_file_paths[i].ToCharArray(), _blend, _is_folder);
                            /*if (tmpptr != null)
                                if (Program.form1.DrawToPictureBox(tmpptr, pBuffer.Width, pBuffer.Height) == 0)
                                    continue;
                                else
                                {
                                    MessageBox.Show("Picture Size Error!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                    break;
                                }
                            else
                            {
                                //MessageBox.Show("Picture Size Error!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                //break;
                            }*/
                        }

                        _jobComplete();
                        if (tmpptr != null)
                            if (Program.form1.DrawToPictureBox(tmpptr, width, height) != 0)
                                MessageBox.Show("Picture Size Error!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);

                        Program.form1.SetProgress(1.0f);
                        Program.form1.unlockButton();
                        return 0;
                    }
                    else
                        MessageBox.Show("Output folder does not exists!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                else
                    MessageBox.Show("Input folder does not exists!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else
            {
                if (File.Exists(_input_path))
                {
                    if (Directory.Exists(_output_path.Substring(0, _output_path.LastIndexOf('\\'))))
                    {
                        int width = _getWidth(_input_path.ToCharArray());
                        int height = _getHeight(_input_path.ToCharArray());
                        Console.WriteLine(width.ToString());
                        Console.WriteLine(height.ToString());
                        if (width == -1 || height == -1)
                        {
                            MessageBox.Show("Picture Format Error!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            Program.form1.unlockButton();
                            return -1;
                        }

                        _jobStart(width, height, _blend);
                        IntPtr tmpptr = _denoiseImplement(_input_path.ToCharArray(), _output_path.ToCharArray(), _blend, _is_folder);
                        if (tmpptr != null)
                        {
                            if (Program.form1.DrawToPictureBox(tmpptr, width, height) == -1)
                                MessageBox.Show("Picture Size Error(NULL to Draw)!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                        else
                            MessageBox.Show("Picture Size Error!(NULL Return)", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        Program.form1.SetProgress(1.0f);
                        Program.form1.unlockButton();
                        _jobComplete();
                        return 0;
                    }
                    else
                        MessageBox.Show("Output folder does not exists!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                else
                    MessageBox.Show("Input file does not exists!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            Program.form1.unlockButton();
            return -1;
        }

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 : ConfigHandler.cs
License : GNU General Public License v3.0
Project Creator : 2dust

public static int AddBatchServers(ref Config config, string clipboardData, string subid = "")
        {
            if (Utils.IsNullOrEmpty(clipboardData))
            {
                return -1;
            }
            //if (clipboardData.IndexOf("vmess") >= 0 && clipboardData.IndexOf("vmess") == clipboardData.LastIndexOf("vmess"))
            //{
            //    clipboardData = clipboardData.Replace("\r\n", "").Replace("\n", "");
            //}
            int countServers = 0;

            //string[] arrData = clipboardData.Split(new string[] { "\r\n" }, StringSplitOptions.None);
            string[] arrData = clipboardData.Split(Environment.NewLine.ToCharArray());
            foreach (string str in arrData)
            {
                //maybe sub
                if (str.StartsWith(Global.httpsProtocol) || str.StartsWith(Global.httpProtocol))
                {
                    if (AddSubItem(ref config, str) == 0)
                    {
                        countServers++;
                    }
                    continue;
                }
                VmessItem vmessItem = ShareHandler.ImportFromClipboardConfig(str, out string msg);
                if (vmessItem == null)
                {
                    continue;
                }
                vmessItem.subid = subid;
                if (vmessItem.configType == (int)EConfigType.Vmess)
                {
                    if (AddServer(ref config, vmessItem, -1, false) == 0)
                    {
                        countServers++;
                    }
                }
                else if (vmessItem.configType == (int)EConfigType.Shadowsocks)
                {
                    if (AddShadowsocksServer(ref config, vmessItem, -1, false) == 0)
                    {
                        countServers++;
                    }
                }
                else if (vmessItem.configType == (int)EConfigType.Socks)
                {
                    if (AddSocksServer(ref config, vmessItem, -1, false) == 0)
                    {
                        countServers++;
                    }
                }
                else if (vmessItem.configType == (int)EConfigType.Trojan)
                {
                    if (AddTrojanServer(ref config, vmessItem, -1, false) == 0)
                    {
                        countServers++;
                    }
                }
                else if (vmessItem.configType == (int)EConfigType.VLESS)
                {
                    if (AddVlessServer(ref config, vmessItem, -1, false) == 0)
                    {
                        countServers++;
                    }
                }
            }
            ToJsonFile(config);
            return countServers;
        }

19 View Source File : StatisticsHandler.cs
License : GNU General Public License v3.0
Project Creator : 2dust

private void ParseOutput(Google.Protobuf.Collections.RepeatedField<Stat> source, out ulong up, out ulong down)
        {

            up = 0; down = 0;
            try
            {

                foreach (Stat stat in source)
                {
                    string name = stat.Name;
                    long value = stat.Value;
                    string[] nStr = name.Split(">>>".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
                    string type = "";

                    name = name.Trim();

                    name = nStr[1];
                    type = nStr[3];

                    if (name == Global.agentTag)
                    {
                        if (type == "uplink")
                        {
                            up = (ulong)value;
                        }
                        else if (type == "downlink")
                        {
                            down = (ulong)value;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                //Utils.SaveLog(ex.Message, ex);
            }
        }

19 View Source File : GrblSettingsWindow.xaml.cs
License : MIT License
Project Creator : 3RD-Dimension

public void LineReceived(string line)
        {
            // Recieve GRBL Controller Version number and display - $i
            // Recieved in format [VER: ... and [OPT:

            if (!line.StartsWith("$") && !line.StartsWith("[VER:") && !line.StartsWith("[OPT:"))
                return;

            if (line.StartsWith("$"))
            {
                try
                {
                    Match m = settingParser.Match(line);
                    int number = int.Parse(m.Groups[1].Value);
                    double value = double.Parse(m.Groups[2].Value, Util.Constants.DecimalParseFormat);

                    // Value = Setting Value, Number = Setting Code

                    if (!CurrentSettings.ContainsKey(number))
                    {
                        RowDefinition rowDef = new RowDefinition();
                        rowDef.Height = new GridLength(25);
                        gridMain.RowDefinitions.Add(rowDef);

                        TextBox valBox = new TextBox // Value of Setting Textbox
                        {
                            Text = value.ToString(Util.Constants.DecimalOutputFormat),
                            VerticalAlignment = VerticalAlignment.Center
                        };

                        // Define Mouseclick for textbox to open GRBLStepsCalcWindow for setting $100, $101, $102
                        if (number == 100) { valBox.Name = "Set100"; valBox.MouseDoubleClick += openStepsCalc; }
                        else if (number == 101) { valBox.Name = "Set101"; valBox.MouseDoubleClick += openStepsCalc; }
                        else if (number == 102) { valBox.Name = "Set102"; valBox.MouseDoubleClick += openStepsCalc; }
                        Grid.SetRow(valBox, gridMain.RowDefinitions.Count - 1);
                        Grid.SetColumn(valBox, 1);
                        gridMain.Children.Add(valBox);

                        TextBlock num = new TextBlock
                        {
                            Text = $"${number}=",
                            HorizontalAlignment = HorizontalAlignment.Right,
                            VerticalAlignment = VerticalAlignment.Center
                        };
                        Grid.SetRow(num, gridMain.RowDefinitions.Count - 1);
                        Grid.SetColumn(num, 0);
                        gridMain.Children.Add(num);

                        if (Util.GrblCodeTranslator.Settings.ContainsKey(number))
                        {
                            Tuple<string, string, string> labels = Util.GrblCodeTranslator.Settings[number];

                            TextBlock name = new TextBlock
                            {
                                Text = labels.Item1,
                                VerticalAlignment = VerticalAlignment.Center
                            };
                            Grid.SetRow(name, gridMain.RowDefinitions.Count - 1);
                            Grid.SetColumn(name, 0);
                            gridMain.Children.Add(name);

                            TextBlock unit = new TextBlock
                            {
                                Text = labels.Item2,
                                VerticalAlignment = VerticalAlignment.Center
                            };
                            Grid.SetRow(unit, gridMain.RowDefinitions.Count - 1);
                            Grid.SetColumn(unit, 2);
                            gridMain.Children.Add(unit);

                            valBox.ToolTip = $"{labels.Item1} ({labels.Item2}):\n{labels.Item3}";
                        }

                        CurrentSettings.Add(number, value);
                        SettingsBoxes.Add(number, valBox);
                    }
                    else
                    {
                        SettingsBoxes[number].Text = value.ToString(Util.Constants.DecimalOutputFormat);
                        CurrentSettings[number] = value;
                    }
                }
                catch { }
            }
            // If the line starts with [VER: then we know we are getting the version and options
            else if (line.StartsWith("[VER:") || line.StartsWith("[OPT:"))
            {
                // Frist need to remove front [ and rear ]
                string VerOptInput; // Input string
                string[] VerOptTrimmed;
                VerOptInput = line.Remove(0, 1); // Remove [ from the start
                VerOptInput = VerOptInput.Remove(VerOptInput.Length - 1);

                // Next, split the values in half at the : - we only want VER/OPT and then the values
                VerOptTrimmed = VerOptInput.Split(':');

                // Now we fill in the boxes depending on which one
                switch (VerOptTrimmed[0])
                {
                    case "VER":
                        controllerInfo += "Version: " + VerOptTrimmed[1];
                        break;

                    case "OPT":
                        // First we have to split commas
                        string[] optSplit;
                        optSplit = VerOptTrimmed[1].Split(','); // Splits Options into 3.  0=Options, 1=blockBufferSize, 2=rxBufferSize
                        var individualChar = optSplit[0].ToCharArray();// Now split optSplit[0] into each option character

                        controllerInfo += " | Options: " + VerOptTrimmed[1]; // Full Options Non-Decoded String

                        foreach (char c in individualChar)
                        {
                            // Lookup what each code is and display....  buildCodes Dictionary
                            if (Util.GrblCodeTranslator.BuildCodes.ContainsKey(c.ToString()))
                            {
                                // Now lets try and create and append to a string and then bind it to a ToolTip? or some other way
                                controllerInfo += Environment.NewLine + Util.GrblCodeTranslator.BuildCodes[c.ToString()];
                            }
                        }
                        controllerInfo += Environment.NewLine + "Block Buffer Size: " + optSplit[1];
                        controllerInfo += Environment.NewLine + "RX Buffer Size: " + optSplit[2];
                        GRBL_Controller_Info.Text = controllerInfo.ToString();
                        break;
                }
            }
        }

19 View Source File : StringFuzzer.cs
License : Apache License 2.0
Project Creator : 42skillz

public string GenerateStringFromPattern(string diverseFormat)
        {
            var builder = new StringBuilder(diverseFormat.Length);
            foreach (var c in diverseFormat.ToCharArray())
            {
                switch (c)
                {
                    case '#':
                        builder.Append(_fuzzer.GenerateInteger(0,9));
                        break;

                    case 'X': builder.Append(_fuzzer.GenerateLetter().ToString().ToUpper());
                        break;

                    case 'x': builder.Append(_fuzzer.GenerateLetter());
                        break;

                    default: builder.Append(c);
                        break;
                }
            }

            return builder.ToString();
        }

19 View Source File : HolidayUtil.cs
License : MIT License
Project Creator : 6tail

private static Holiday buildHolidayForward(string s)
        {
            char[] chars = s.Substring(8, 2).ToCharArray();
            string day = s.Substring(0, 8);
            string name = NAMES_IN_USE[chars[0] - ZERO];
            bool work = chars[1] == ZERO;
            string target = s.Substring(10, 8);
            return new Holiday(day, name, work, target);
        }

19 View Source File : HolidayUtil.cs
License : MIT License
Project Creator : 6tail

private static Holiday buildHolidayBackward(string s)
        {
            int size = s.Length;
            char[] chars = s.Substring(size - 10, 2).ToCharArray();
            string day = s.Substring(size - 18, 8);
            string name = NAMES_IN_USE[chars[0] - ZERO];
            bool work = chars[1] == ZERO;
            string target = s.Substring(size - 8);
            return new Holiday(day, name, work, target);
        }

19 View Source File : Foto.cs
License : MIT License
Project Creator : 6tail

public string getYearInChinese()
        {
            char[] y = (getYear() + "").ToCharArray();
            StringBuilder s = new StringBuilder();
            for (int i = 0, j = y.Length; i < j; i++)
            {
                s.Append(LunarUtil.NUMBER[y[i] - '0']);
            }
            return s.ToString();
        }

19 View Source File : LINQ.cs
License : MIT License
Project Creator : 71

[Fact]
        public void ShouldTransformQuery()
        {
            IEnumerable<int> items = Enumerable.Range(0, 100);

            Expression body = X.Express(() => from item in items
                                              where item > 0
                                              let cube = item * item * item
                                              from ch in cube.ToString().ToCharArray()
                                              select $"{cube}{ch}");

            QueryExpression query = X.Query(body);
        }

19 View Source File : String.Extension.cs
License : MIT License
Project Creator : 7Bytes-Studio

public static string Replace(this string str,string replaceOp)
        {
            if (!replaceOp.Contains(":") || !replaceOp.Contains("|")) throw new System.Exception("操作必需符合 lop:rop|your replace string");

            string sliceOp = replaceOp.Split('|')[0].Trim();
            string replaceStr = replaceOp.Slice(string.Format("{0}:", sliceOp.Length+1));

            var strArr = str.ToCharArray();

            if (sliceOp == ":") // ":"
            {
                return replaceStr;
            }
            else if (sliceOp[0] == ':') //":xxx"
            {
                var s = sliceOp.Split(':');
                int lop = 0;
                int rop = int.Parse(s[1]);
                int replaceStrIndex = 0;
                for (int i = lop; i < rop; i++)
                {
                    if (replaceStrIndex < replaceStr.Length)
                    {
                        strArr[i] = replaceStr[replaceStrIndex++];
                    }
                }

                return new string(strArr);
            }
            else if (sliceOp[sliceOp.Length - 1] == ':') //"xxx:"
            {
                var s = sliceOp.Split(':');
                int lop = int.Parse(s[0]);
                lop = 0 > lop ? strArr.Length + lop : lop;
                int rop = strArr.Length;
                int replaceStrIndex = 0;
                for (int i = lop; i < rop; i++)
                {
                    if (replaceStrIndex < replaceStr.Length)
                    {
                        strArr[i] = replaceStr[replaceStrIndex++];
                    }
                }

                return new string(strArr);
            }
            else//"xxx:xxx"
            {
                var s = sliceOp.Split(':');
                int lop = int.Parse(s[0]);
                int rop = int.Parse(s[1]);
                int replaceStrIndex = 0;
                for (int i = lop; i < rop; i++)
                {
                    if (replaceStrIndex < replaceStr.Length)
                    {
                        strArr[i] = replaceStr[replaceStrIndex++];
                    }           
                }

                return new string(strArr);
            }
        }

19 View Source File : String.Extension.cs
License : MIT License
Project Creator : 7Bytes-Studio

public static string Slice(this string str, char sliceLChar,char sliceRChar)
        {
            var arr = str.ToCharArray();
            List<char> charArr = new List<char>();
            bool startRead = false;
            for (int i = 0; i < arr.Length; i++)
            {
                if (arr[i]==sliceLChar)
                {
                    startRead = true;
                    continue;
                }
                else if (arr[i] == sliceRChar)
                {
                    startRead = false;
                    return new string(charArr.ToArray());
                }

                if (startRead)
                {
                    charArr.Add(arr[i]);
                }
            }
            return string.Empty;
        }

19 View Source File : CloudSwap.cs
License : GNU Lesser General Public License v3.0
Project Creator : 9and3

protected override void SolveInstance(IGH_DataAccess DA) {

            GH_Cloud cloud = new GH_Cloud();
            DA.GetData(0, ref cloud);

            string txt = "CPN";
            DA.GetData(1, ref txt);

            char[] characters = txt.ToCharArray();

            if (characters == null) return;
            if (characters.Length != 3) return;

            Point3d[] points = new Point3d[cloud.Value.Count];
            Vector3d[] normals = new Vector3d[cloud.Value.Count];
            System.Drawing.Color[] colors = new System.Drawing.Color[cloud.Value.Count];

            //PointCloud swapCloud = new PointCloud();

            System.Threading.Tasks.Parallel.For(0, cloud.Value.Count, i => {
                //for (int i = 0; i < cloud.Value.Count; i++) {

                //swapCloud.AppendNew();

                //Points

                switch (characters[0]) {

                    case ('p'):
                    case ('P'):
                        points[i] = cloud.Value[i].Location;

                        break;

                    case ('c'):
                    case ('C'):
                        var color = cloud.Value[i].Color;
                        points[i] = new Point3d(color.R, color.G, color.B);
                        break;

                    case ('n'):
                    case ('N'):
                        points[i] = new Point3d(cloud.Value[i].Normal);
                        break;

                }

                switch (characters[1]) {

                    case ('p'):
                    case ('P'):
                        normals[i] = new Vector3d(cloud.Value[i].Location);

                        break;

                    case ('c'):
                    case ('C'):
                        var color = cloud.Value[i].Color;
                        normals[i] = new Vector3d(color.R, color.G, color.B);
                        break;

                    case ('n'):
                    case ('N'):
                        normals[i] = new Vector3d(cloud.Value[i].Normal);
                        break;

                }

                switch (characters[2]) {

                    case ('p'):
                    case ('P'):
                        colors[i] = cloud.Value[i].Color;

                        break;

                    case ('c'):
                    case ('C'):

                        colors[i] = cloud.Value[i].Color;
                        break;

                    case ('n'):
                    case ('N'):
                        colors[i] = cloud.Value[i].Color;
                        break;

                }

           // }
            });

            PointCloud c = new PointCloud();
            c.AddRange(points,normals,colors);

            DA.SetData(0,new GH_Cloud(c));
        }

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

public static string JoinString(this IEnumerable<string> values, string split)
        {
            var result = values.Aggregate(string.Empty, (current, value) => current + (split + value));
            result = result.TrimStart(split.ToCharArray());
            return result;
        }

19 View Source File : BiffRecordExtensions.cs
License : Apache License 2.0
Project Creator : aaaddress1

private static string HexDump(byte[] bytes, int bytesPerLine = 16)
        {
            if (bytes == null) return "<null>";
            int bytesLength = bytes.Length;

            char[] HexChars = "0123456789ABCDEF".ToCharArray();

            int firstHexColumn =
                  8                   // 8 characters for the address
                + 3;                  // 3 spaces

            int firstCharColumn = firstHexColumn
                + bytesPerLine * 3       // - 2 digit for the hexadecimal value and 1 space
                + (bytesPerLine - 1) / 8 // - 1 extra space every 8 characters from the 9th
                + 2;                  // 2 spaces 

            int lineLength = firstCharColumn
                + bytesPerLine           // - characters to show the ascii value
                + Environment.NewLine.Length; // Carriage return and line feed (should normally be 2)

            char[] line = (new String(' ', lineLength - Environment.NewLine.Length) + Environment.NewLine).ToCharArray();
            int expectedLines = (bytesLength + bytesPerLine - 1) / bytesPerLine;
            StringBuilder result = new StringBuilder(expectedLines * lineLength);

            for (int i = 0; i < bytesLength; i += bytesPerLine)
            {
                line[0] = HexChars[(i >> 28) & 0xF];
                line[1] = HexChars[(i >> 24) & 0xF];
                line[2] = HexChars[(i >> 20) & 0xF];
                line[3] = HexChars[(i >> 16) & 0xF];
                line[4] = HexChars[(i >> 12) & 0xF];
                line[5] = HexChars[(i >> 8) & 0xF];
                line[6] = HexChars[(i >> 4) & 0xF];
                line[7] = HexChars[(i >> 0) & 0xF];

                int hexColumn = firstHexColumn;
                int charColumn = firstCharColumn;

                for (int j = 0; j < bytesPerLine; j++)
                {
                    if (j > 0 && (j & 7) == 0) hexColumn++;
                    if (i + j >= bytesLength)
                    {
                        line[hexColumn] = ' ';
                        line[hexColumn + 1] = ' ';
                        line[charColumn] = ' ';
                    }
                    else
                    {
                        byte b = bytes[i + j];
                        line[hexColumn] = HexChars[(b >> 4) & 0xF];
                        line[hexColumn + 1] = HexChars[b & 0xF];
                        line[charColumn] = (b < 32 ? '·' : (char)b);
                    }
                    hexColumn += 3;
                    charColumn++;
                }
                result.Append(line);
            }
            return result.ToString();
        }

19 View Source File : CharRope.cs
License : MIT License
Project Creator : Abdesol

public static void InsertText(this Rope<char> rope, int index, string text)
		{
			if (rope == null)
				throw new ArgumentNullException("rope");
			rope.InsertRange(index, text.ToCharArray(), 0, text.Length);
			/*if (index < 0 || index > rope.Length) {
				throw new ArgumentOutOfRangeException("index", index, "0 <= index <= " + rope.Length.ToString(CultureInfo.InvariantCulture));
			}
			if (text == null)
				throw new ArgumentNullException("text");
			if (text.Length == 0)
				return;
			rope.root = rope.root.Insert(index, text);
			rope.OnChanged();*/
		}

19 View Source File : EditingCommandHandler.cs
License : MIT License
Project Creator : Abdesol

static string InvertCase(string text)
		{
			CultureInfo culture = CultureInfo.CurrentCulture;
			char[] buffer = text.ToCharArray();
			for (int i = 0; i < buffer.Length; ++i) {
				char c = buffer[i];
				buffer[i] = char.IsUpper(c) ? char.ToLower(c, culture) : char.ToUpper(c, culture);
			}
			return new string(buffer);
		}

19 View Source File : Uuid64.cs
License : MIT License
Project Creator : abdullin

private static bool TryParse(string s, out ulong result)
		{
			Contract.Requires(s != null);

			// we support the following formats: "{hex8-hex8}", "{hex16}", "hex8-hex8", "hex16" and "base62"
			// we don't support base10 format, because there is no way to differentiate from hex or base62

			result = 0;
			switch (s.Length)
			{
				case 19:
					{ // {xxxxxxxx-xxxxxxxx}
						if (s[0] != '{' || s[18] != '}')
						{
							return false;
						}
						return TryDecode16(s.ToCharArray(), 1, true, out result);
					}
				case 18:
					{ // {xxxxxxxxxxxxxxxx}
						if (s[0] != '{' || s[17] != '}')
						{
							return false;
						}
						return TryDecode16(s.ToCharArray(), 1, false, out result);
					}
				case 17:
					{ // xxxxxxxx-xxxxxxxx
						if (s[8] != '-') return false;
						return TryDecode16(s.ToCharArray(), 0, true, out result);
					}
				case 16:
					{ // xxxxxxxxxxxxxxxx
						return TryDecode16(s.ToCharArray(), 0, false, out result);
					}
			}

			// only base62 is allowed
			if (s.Length <= 11)
			{
				return TryDecode62(s.ToCharArray(), out result);
			}

			return false;
		}

19 View Source File : DataEntry.cs
License : MIT License
Project Creator : absurd-joy

public byte[] Serialize()
		{
			using (MemoryStream m = new MemoryStream())
			{
				using (BinaryWriter writer = new BinaryWriter(m))
				{
					// Limit our string to BUFFER_SIZE
					if (textString.Length > Constants.BUFFER_SIZE)
					{
						textString = textString.Substring(0, Constants.BUFFER_SIZE-1);
					}
					writer.Write(packetID);
					writer.Write(textString.ToCharArray());
					writer.Write('\0');
				}
				return m.ToArray();
			}
		}

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

private bool Ends(String s)
        {
            int l = s.Length;
            int o = k - l + 1;
            if (o < 0)
                return false;
            char[] sc = s.ToCharArray();
            for (int i = 0; i < l; i++)
                if (b[o + i] != sc[i])
                    return false;
            j = k - l;
            return true;
        }

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

private void Setto(String s)
        {
            int l = s.Length;
            int o = j + 1;
            char[] sc = s.ToCharArray();
            for (int i = 0; i < l; i++)
                b[o + i] = sc[i];
            k = j + l;
        }

19 View Source File : SecureStringExtensions.cs
License : MIT License
Project Creator : Accelerider

public static SecureString replacedecureString(this string @this)
        {
            if (string.IsNullOrEmpty(@this))
                return new SecureString();

            var secureString = new SecureString();
            Array.ForEach(@this.ToCharArray(), secureString.AppendChar);

            return secureString;
        }

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

public static string Reverse(this string s)
        {
            char[] charArray = s.ToCharArray();
            Array.Reverse(charArray);
            return new string(charArray);
        }

19 View Source File : PropertyAttribute2nd.cs
License : GNU Affero General Public License v3.0
Project Creator : 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 View Source File : FactionBits.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

public static string ToSentence(this FactionBits factionBits)
        {
            return new string(factionBits.ToString().ToCharArray().SelectMany((c, i) => i > 0 && char.IsUpper(c) ? new char[] { ' ', c } : new char[] { c }).ToArray());
        }

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

public static string ToSentence(this HookGroupType hookGroupType)
        {
            return new string(hookGroupType.ToString().ToCharArray().SelectMany((c, i) => i > 0 && char.IsUpper(c) ? new char[] { ' ', c } : new char[] { c }).ToArray());
        }

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

public static string ToSentence(this Skill skill)
        {
            return new string(skill.ToString().ToCharArray().SelectMany((c, i) => i > 0 && char.IsUpper(c) ? new char[] { ' ', c } : new char[] { c }).ToArray());
        }

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

[CommandHandler("bestow", AccessLevel.Advocate, CommandHandlerFlag.RequiresWorld, 2,
            "Sets a character's Advocate Level.",
            "<name> <level>\nAdvocates can bestow any level less than their own.")]
        public static void HandleBestow(Session session, params string[] parameters)
        {
            var charName = string.Join(" ", parameters).Trim();

            var level = parameters[parameters.Length - 1];

            if (!int.TryParse(level, out var advocateLevel) || advocateLevel < 1 || advocateLevel > 7)
            {
                session.Network.EnqueueSend(new GameMessageSystemChat($"{level} is not a valid advocate level.", ChatMessageType.Broadcast));
                return;
            }

            var advocateName = charName.TrimEnd((" " + level).ToCharArray());

            var playerToFind = PlayerManager.FindByName(advocateName);

            if (playerToFind != null)
            {
                if (playerToFind is Player player)
                {
                    //if (!Advocate.IsAdvocate(player))
                    //{
                    //    session.Network.EnqueueSend(new GameMessageSystemChat($"{playerToFind.Name} is not an Advocate.", ChatMessageType.Broadcast));
                    //    return;
                    //}

                    if (player.IsPK || PropertyManager.GetBool("pk_server").Item)
                    {
                        session.Network.EnqueueSend(new GameMessageSystemChat($"{playerToFind.Name} in a Player Killer and cannot be an Advocate.", ChatMessageType.Broadcast));
                        return;
                    }

                    if (session.Player.AdvocateLevel <= player.AdvocateLevel)
                    {
                        session.Network.EnqueueSend(new GameMessageSystemChat($"You cannot change {playerToFind.Name}'s Advocate status because they are equal to or out rank you.", ChatMessageType.Broadcast));
                        return;
                    }

                    if (advocateLevel >= session.Player.AdvocateLevel && !session.Player.IsAdmin)
                    {
                        session.Network.EnqueueSend(new GameMessageSystemChat($"You cannot bestow {playerToFind.Name}'s Advocate rank to {advocateLevel} because that is equal to or higher than your rank.", ChatMessageType.Broadcast));
                        return;
                    }

                    if (advocateLevel == player.AdvocateLevel)
                    {
                        session.Network.EnqueueSend(new GameMessageSystemChat($"{playerToFind.Name}'s Advocate rank is already at level {advocateLevel}.", ChatMessageType.Broadcast));
                        return;
                    }

                    if (!Advocate.CanAcceptAdvocateItems(player, advocateLevel))
                    {
                        session.Network.EnqueueSend(new GameMessageSystemChat($"You cannot change {playerToFind.Name}'s Advocate status because they do not have capacity for the advocate items.", ChatMessageType.Broadcast));
                        return;
                    }

                    if (Advocate.Bestow(player, advocateLevel))
                        session.Network.EnqueueSend(new GameMessageSystemChat($"{playerToFind.Name} is now an Advocate, level {advocateLevel}.", ChatMessageType.Broadcast));
                    else
                        session.Network.EnqueueSend(new GameMessageSystemChat($"Advocate bestowal of {playerToFind.Name} failed.", ChatMessageType.Broadcast));
                }
                else
                    session.Network.EnqueueSend(new GameMessageSystemChat($"{playerToFind.Name} is not online. Cannot complete bestowal process.", ChatMessageType.Broadcast));
            }
            else
                session.Network.EnqueueSend(new GameMessageSystemChat($"{advocateName} was not found in the database.", ChatMessageType.Broadcast));
        }

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

public static DateTime ToDateTime(string dateValue)
        {
            if (string.IsNullOrEmpty(dateValue))
            {
                return new DateTime();
            }

            var date = dateValue.Trim();
            // ReSharper disable once InconsistentNaming
            const string DateDelimiters = @"-.\/_ ";
            char[] c = DateDelimiters.ToCharArray();
            int d2 = date.LastIndexOfAny(c);
            int d1 = date.IndexOfAny(c);

            try
            {
                string year = string.Empty;
                string month = string.Empty;
                string day = string.Empty;
                if (date.Length > d2 + 1)
                {
                    year = date.Substring(d2 + 1);
                }
                if (date.Length > (d1 + 1) && (d2 - d1 - 1) < date.Length - (d1 + 1))
                {
                    month = date.Substring(d1 + 1, d2 - d1 - 1);
                }
                if (date.Length > 0 && d1 <= date.Length)
                {
                    day = date.Substring(0, d1);
                }
                return new DateTime(
                    Convert.ToInt32(year, CultureInfo.InvariantCulture),
                    Convert.ToInt32(month, CultureInfo.InvariantCulture),
                    Convert.ToInt32(day, CultureInfo.InvariantCulture));
            }
            catch (ArgumentOutOfRangeException e)
            {
                Debug.WriteLine("Error in ToDateTime:" + e.Message);
                return new DateTime();
            }
            catch (FormatException e)
            {
                Debug.WriteLine("Error in ToDateTime:" + e.Message);
                return new DateTime();
            }
            catch (OverflowException e)
            {
                Debug.WriteLine("Error in ToDateTime:" + e.Message);
                return new DateTime();
            }
        }

19 View Source File : PowerBIPartConverters.cs
License : MIT License
Project Creator : action-bi-toolkit

public static string ConvertToValidModelName(string name)
        { 
            const string
                forbiddenCharacters =
                    @". , ; ' ` : / \ * | ? "" & % $ ! + = ( ) [ ] { } < >"; // grabbed these from an AMO exception message
            var modelName = forbiddenCharacters // TODO Could also use TOM.Server.Databases.CreateNewName()
                .Replace(" ", "")
                .ToCharArray()
                .Aggregate(
                    name,
                    (n, c) => n.Replace(c, '_')
                );
            return modelName;
        }

19 View Source File : CustomShellService.cs
License : MIT License
Project Creator : Actipro

private string CombineCloudStorageParsingNames(params string[] relativeParsingNames) {
			if (relativeParsingNames is null || relativeParsingNames.Length == 0)
				return null;

			string parsingName = relativeParsingNames[0].TrimEnd(CloudStorageParsingNameSeparator.ToCharArray());
			for (int i = 1; i < relativeParsingNames.Length; i++) {
				parsingName += CloudStorageParsingNameSeparator + relativeParsingNames[i].Trim(CloudStorageParsingNameSeparator.ToCharArray());
			}

			return parsingName;
		}

19 View Source File : TypoInViewDelegateNameFix.cs
License : GNU General Public License v3.0
Project Creator : Acumatica

private static string GenerateViewDelegateName(string viewName)
		{
			var chars = viewName.ToCharArray();
			char firstChar = chars[0];
			if (Char.IsUpper(firstChar))
			{
				firstChar = Char.ToLowerInvariant(firstChar);
			}
			else if (Char.IsLower(firstChar))
			{
				firstChar = Char.ToUpperInvariant(firstChar);
			}

			chars[0] = firstChar;

			return new string(chars);
		}

19 View Source File : MiniJson.cs
License : MIT License
Project Creator : AdamCarballo

void SerializeString(string str) {
				builder.Append('\"');
				
				char[] charArray = str.ToCharArray();
				foreach (var c in charArray) {
					switch (c) {
					case '"':
						builder.Append("\\\"");
						break;
					case '\\':
						builder.Append("\\\\");
						break;
					case '\b':
						builder.Append("\\b");
						break;
					case '\f':
						builder.Append("\\f");
						break;
					case '\n':
						builder.Append("\\n");
						break;
					case '\r':
						builder.Append("\\r");
						break;
					case '\t':
						builder.Append("\\t");
						break;
					default:
						int codepoint = Convert.ToInt32(c);
						if ((codepoint >= 32) && (codepoint <= 126)) {
							builder.Append(c);
						} else {
							builder.Append("\\u");
							builder.Append(codepoint.ToString("x4"));
						}
						break;
					}
				}
				
				builder.Append('\"');
			}

19 View Source File : AdColonyUtils.cs
License : Apache License 2.0
Project Creator : AdColony

void SerializeString(string aString, StringBuilder builder)
        {
            builder.Append("\"");

            char[] charArray = aString.ToCharArray();
            for (int i = 0; i < charArray.Length; i++)
            {
                char c = charArray[i];
                if (c == '"')
                {
                    builder.Append("\\\"");
                }
                else if (c == '\\')
                {
                    builder.Append("\\\\");
                }
                else if (c == '\b')
                {
                    builder.Append("\\b");
                }
                else if (c == '\f')
                {
                    builder.Append("\\f");
                }
                else if (c == '\n')
                {
                    builder.Append("\\n");
                }
                else if (c == '\r')
                {
                    builder.Append("\\r");
                }
                else if (c == '\t')
                {
                    builder.Append("\\t");
                }
                else
                {
                    int codepoint = Convert.ToInt32(c);
                    if ((codepoint >= 32) && (codepoint <= 126))
                    {
                        builder.Append(c);
                    }
                    else
                    {
                        builder.Append("\\u" + Convert.ToString(codepoint, 16).PadLeft(4, '0'));
                    }
                }
            }

            builder.Append("\"");
        }

19 View Source File : AdColonyUtils.cs
License : Apache License 2.0
Project Creator : AdColony

public static object Decode(string json)
        {
            if (json == null)
            {
                return null;
            }

            // save the string for debug information
            AdColonyJson.instance.lastDecode = json;

            object value = null;
            try
            {
                char[] charArray = json.ToCharArray();
                int index = 0;
                bool success = true;
                value = AdColonyJson.instance.ParseValue(charArray, ref index, ref success);
                if (success)
                {
                    AdColonyJson.instance.lastErrorIndex = -1;
                }
                else
                {
                    AdColonyJson.instance.lastErrorIndex = index;
                }
            }
            catch (System.Exception e)
            {
                UnityEngine.Debug.LogError(e.ToString());
            }

            return value;
        }

19 View Source File : VCalendar.cs
License : MIT License
Project Creator : Adoxio

public static void AppendField(StringBuilder vevent, string name, string value, bool encodeValue = true)
		{
			// If there's no value, don't append the field at all.
			if (string.IsNullOrEmpty(value))
			{
				return;
			}

			// Get all the characters of the field (name + value), and break it into 72-character lines.
			var fieldCharacters = (name + ":" + (encodeValue ? EncodeValue(value) : value)).ToCharArray();

			for (var i = 0; i < fieldCharacters.Length; i++)
			{
				vevent.Append(fieldCharacters[i]);

				// If we are at the end of the field, write a CRLF.
				if (i == (fieldCharacters.Length - 1))
				{
					vevent.Append("\r\n");
				}
					// If we are at a 72 character boundary (but not the end), write a CRLF plus a space.
				else if (i != 0 && i % 72 == 0)
				{
					vevent.Append("\r\n ");
				}
			}
		}

19 View Source File : deviceidmanager.cs
License : MIT License
Project Creator : Adoxio

private static string GenerateRandomString(string characterSet, int count)
		{
			//Create an array of the characters that will hold the final list of random characters
			char[] value = new char[count];

			//Convert the character set to an array that can be randomly accessed
			char[] set = characterSet.ToCharArray();

			lock (RandomInstance)
			{
				//Populate the array with random characters from the character set
				for (int i = 0; i < count; i++)
				{
					value[i] = set[RandomInstance.Next(0, set.Length)];
				}
			}

			return new string(value);
		}

19 View Source File : StringExtend.cs
License : GNU General Public License v3.0
Project Creator : aduskin

public static string GetFirstPinyin(string str)
      {
         if (str == null || str.Length <= 0)
            return "*";
         char[] charArray = str.ToCharArray();
         return GetPinyinChar(charArray[0]);
      }

19 View Source File : StringExtend.cs
License : GNU General Public License v3.0
Project Creator : aduskin

public static string GetPinyin(string str)
      {
         string pinyin = "";
         char[] charArray = str.ToCharArray();
         foreach (var item in charArray)
         {
            pinyin += GetPinyinChar(item);
         }
         return pinyin;
      }

19 View Source File : Pack.cs
License : Apache License 2.0
Project Creator : aequabit

public object[] Deserialize(byte[] data)
    {
        MemoryStream Stream = new MemoryStream(data);
        BinaryReader Reader = new BinaryReader(Stream, Encoding.UTF8);
        List<object> Items = new List<object>();
        byte Current = 0;
        byte Count = Reader.ReadByte();

        for (int I = 0; I <= Count - 1; I++)
        {
            Current = Reader.ReadByte();

            switch (Current)
            {
                case 0:
                    Items.Add(Reader.ReadBoolean());
                    break;
                case 1:
                    Items.Add(Reader.ReadByte());
                    break;
                case 2:
                    Items.Add(Reader.ReadBytes(Reader.ReadInt32()));
                    break;
                case 3:
                    Items.Add(Reader.ReadChar());
                    break;
                case 4:
                    Items.Add(Reader.ReadString().ToCharArray());
                    break;
                case 5:
                    Items.Add(Reader.ReadDecimal());
                    break;
                case 6:
                    Items.Add(Reader.ReadDouble());
                    break;
                case 7:
                    Items.Add(Reader.ReadInt32());
                    break;
                case 8:
                    Items.Add(Reader.ReadInt64());
                    break;
                case 9:
                    Items.Add(Reader.ReadSByte());
                    break;
                case 10:
                    Items.Add(Reader.ReadInt16());
                    break;
                case 11:
                    Items.Add(Reader.ReadSingle());
                    break;
                case 12:
                    Items.Add(Reader.ReadString());
                    break;
                case 13:
                    Items.Add(Reader.ReadUInt32());
                    break;
                case 14:
                    Items.Add(Reader.ReadUInt64());
                    break;
                case 15:
                    Items.Add(Reader.ReadUInt16());
                    break;
                case 16:
                    Items.Add(DateTime.FromBinary(Reader.ReadInt64()));
                    break;
            }
        }

        Reader.Close();
        return Items.ToArray();
    }

19 View Source File : CreditCardNumberValidator.cs
License : MIT License
Project Creator : afucher

private bool IsValidLuhnAlgorithm(string cleanCreditCardNumber)
        {
            // Store the last digit (check digit)
            var checkDigit = cleanCreditCardNumber[cleanCreditCardNumber.Length - 1];

            // Remove the last digit (check digit)
            cleanCreditCardNumber = cleanCreditCardNumber.Remove(cleanCreditCardNumber.Length - 1);

            // Reverse all digits
            cleanCreditCardNumber = new string(cleanCreditCardNumber.Reverse().ToArray());

            // Convert the clean credit card number into a int list
            var creditCardNumArr = cleanCreditCardNumber.ToCharArray().Select(x => (int)char.GetNumericValue(x)).ToList();

            // Multiply odd position digits by 2
            var creditCardNumArrTemp = new List<int>();
            for (int i = 0; i < creditCardNumArr.Count; i++)
            {
                if ((i + 1) % 2 != 0)
                {
                    creditCardNumArrTemp.Add(creditCardNumArr[i] * 2);
                }
                else
                {
                    creditCardNumArrTemp.Add(creditCardNumArr[i]);
                }
            }
            creditCardNumArr = creditCardNumArrTemp;

            // Subtract 9 to all numbers above 9
            creditCardNumArr = creditCardNumArr.Select(x =>
            {
                if (x > 9)
                {
                    return x - 9;
                }
                return x;
            }).ToList();

            // Get numbers total
            var ccNumbersTotal = creditCardNumArr.Sum();

            // Get modulo of total
            var moduloOfNumbersTotal = (10 - (ccNumbersTotal % 10)) % 10;

            // If modulo of total is equal to the check digit
            return moduloOfNumbersTotal == (int)char.GetNumericValue(checkDigit);
        }

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

private static long DecodingSubcode(string subSegment)
        {
            long result = 0;

            var buildStack = new Stack<char>();

            foreach (var number in subSegment.ToCharArray())
            {
                buildStack.Push(number);
            }

            var length = buildStack.Count;

            for (var i = 0; i < length; i++)
            {
                result += SmallFlakes.elementsTalbe.IndexOf(buildStack.Pop()) * (long)Math.Pow(SmallFlakes.newBaseCount, i);
            }

            return result;
        }

19 View Source File : DesktopScreenShare.cs
License : MIT License
Project Creator : AgoraIO

private void OnStartShareBtnClick()
    {
        if (_startShareBtn != null) _startShareBtn.gameObject.SetActive(false);
        if (_stopShareBtn != null) _stopShareBtn.gameObject.SetActive(true);
        mRtcEngine.StopScreenCapture();

        if (_winIdSelect == null) return;
        var option = _winIdSelect.options[_winIdSelect.value].text;
        if (string.IsNullOrEmpty(option)) return;
        if (option.Contains("|"))
        {
            var windowId = option.Split("|".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)[1];
            _logger.UpdateLog(string.Format(">>>>> Start sharing {0}", windowId));
            mRtcEngine.StartScreenCaptureByWindowId(int.Parse(windowId), default(Rectangle),
                default(ScreenCaptureParameters));
        }
        else
        {
#if UNITY_EDITOR_OSX || UNITY_STANDALONE_OSX
            var dispId = uint.Parse(option.Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)[1]);
            _logger.UpdateLog(string.Format(">>>>> Start sharing display {0}", dispId));
            mRtcEngine.StartScreenCaptureByDisplayId(dispId, default(Rectangle),
                new ScreenCaptureParameters {captureMouseCursor = true, frameRate = 30});
#elif UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN
            var diapFlag = uint.Parse(option.Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)[1]);
            var screenRect = new Rectangle
            {
                x = _dispRect[diapFlag].left,
                y = _dispRect[diapFlag].top,
                width = _dispRect[diapFlag].right - _dispRect[diapFlag].left,
                height = _dispRect[diapFlag].bottom - _dispRect[diapFlag].top
            };
            _logger.UpdateLog(string.Format(">>>>> Start sharing display {0}: {1} {2} {3} {4}", diapFlag, screenRect.x,
                screenRect.y, screenRect.width, screenRect.height));
            var ret = mRtcEngine.StartScreenCaptureByScreenRect(screenRect,
                new Rectangle {x = 0, y = 0, width = 0, height = 0}, default(ScreenCaptureParameters));
#endif
        }
    }

19 View Source File : LicensePacker.cs
License : MIT License
Project Creator : AhmedMinegames

[STAThread]
        static void Main()
        {
            try
            {
                bool IsPresent = false;
                CheckRemoteDebuggerPresent(Process.GetCurrentProcess().Handle, ref IsPresent);
                if (Debugger.IsAttached || IsDebuggerPresent() || IsPresent || CloseHandleAntiDebug())
                {
                    Environment.Exit(0);
                }
                else
                {
                    if (!File.Exists(Environment.CurrentDirectory + @"\SOS13"))
                    {
                        MessageBox.Show("Please Make a SOS13 file in the current program directory and enter the program license to it to continue.", "License Not Found", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning);
                    }
                    else
                    {
                        IntPtr NtdllModule = GetModuleHandle("ntdll.dll");
                        IntPtr DbgUiRemoteBreakinAddress = GetProcAddress(NtdllModule, "DbgUiRemoteBreakin");
                        IntPtr DbgUiConnectToDbgAddress = GetProcAddress(NtdllModule, "DbgUiConnectToDbg");
                        byte[] Int3InvaildCode = { 0xCC };
                        WriteProcessMemory(Process.GetCurrentProcess().Handle, DbgUiRemoteBreakinAddress, Int3InvaildCode, 6, 0);
                        WriteProcessMemory(Process.GetCurrentProcess().Handle, DbgUiConnectToDbgAddress, Int3InvaildCode, 6, 0);
                        string License = File.ReadAllText(Environment.CurrentDirectory + @"\SOS13");
                        if (string.IsNullOrEmpty(License))
                        {
                            Environment.Exit(0);
                        }
                        else
                        {
                            StringBuilder NewLicense = new StringBuilder();
                            for (int c = 0; c < License.Length; c++)
                                NewLicense.Append((char)((uint)License[c] ^ (uint)Convert.FromBase64String("decryptkeyencryption")[c % 4]));
                            StringBuilder ROT13Encoding = new StringBuilder();
                            Regex regex = new Regex("[A-Za-z]");
                            foreach (char KSXZ in NewLicense.ToString())
                            {
                                if (regex.IsMatch(KSXZ.ToString()))
                                {
                                    int C = ((KSXZ & 223) - 52) % 26 + (KSXZ & 32) + 65;
                                    ROT13Encoding.Append((char)C);
                                }
                            }
                            StringBuilder sb = new StringBuilder(); foreach (char c in ROT13Encoding.ToString().ToCharArray()) { sb.Append(Convert.ToString(c, 2).PadLeft(8, '0')); }
                            var GetTextToHEX = Encoding.Unicode.GetBytes(sb.ToString());
                            var BuildHEX = new StringBuilder();
                            foreach (var FinalHEX in GetTextToHEX)
                            {
                                BuildHEX.Append(FinalHEX.ToString("X2"));
                            }
                            string HashedKey = UTF8Encoding.UTF8.GetString(MD5.Create().ComputeHash(UTF8Encoding.UTF8.GetBytes(BuildHEX.ToString())));
                            HMACMD5 HMACMD = new HMACMD5();
                            HMACMD.Key = UTF8Encoding.UTF8.GetBytes("LXSO12");
                            string HashedKey2 = UTF8Encoding.UTF8.GetString(HMACMD.ComputeHash(UTF8Encoding.UTF8.GetBytes(HashedKey)));
                            string DecryptedProgram = TqMIJUcgsXjVgxqJ(ProgramToDecrypt, HashedKey2.ToString(), IV);
                            byte[] ProgramToRun = Convert.FromBase64String(DecryptedProgram);
                            replacedembly RunInMemory = replacedembly.Load(ProgramToRun);
                            RunInMemory.EntryPoint.Invoke(null, null);
                        }
                    }
                }
            }
            catch (CryptographicException)
            {
                MessageBox.Show("Sorry, but looks like your license key are invalid.", "Error", MessageBoxButtons.OKCancel, MessageBoxIcon.Error);
            }
        }

19 View Source File : Program.cs
License : MIT License
Project Creator : AhmedMinegames

[STAThread]
        static void Main()
        {
            try
            {
                bool IsPresent = false;
                CheckRemoteDebuggerPresent(Process.GetCurrentProcess().Handle, ref IsPresent);
                if (Debugger.IsAttached || IsDebuggerPresent() || IsPresent || CloseHandleAntiDebug())
                {
                    Environment.Exit(0);
                }
                else
                {
                    IntPtr NtdllModule = GetModuleHandle("ntdll.dll");
                    IntPtr DbgUiRemoteBreakinAddress = GetProcAddress(NtdllModule, "DbgUiRemoteBreakin");
                    IntPtr DbgUiConnectToDbgAddress = GetProcAddress(NtdllModule, "DbgUiConnectToDbg");
                    byte[] Int3InvaildCode = { 0xCC };
                    WriteProcessMemory(Process.GetCurrentProcess().Handle, DbgUiRemoteBreakinAddress, Int3InvaildCode, 6, 0);
                    WriteProcessMemory(Process.GetCurrentProcess().Handle, DbgUiConnectToDbgAddress, Int3InvaildCode, 6, 0);
                    string HWID = GetHardwareID();
                    StringBuilder DecryptEncryptionKey = new StringBuilder();
                    for (int c = 0; c < HWID.Length; c++)
                        DecryptEncryptionKey.Append((char)((uint)HWID[c] ^ (uint)Convert.FromBase64String("SOS12")[c % 4]));
                    StringBuilder ROT13Encoding = new StringBuilder();
                    Regex regex = new Regex("[A-Za-z]");
                    foreach (char KSXZ in DecryptEncryptionKey.ToString())
                    {
                        if (regex.IsMatch(KSXZ.ToString()))
                        {
                            int C = ((KSXZ & 223) - 52) % 26 + (KSXZ & 32) + 65;
                            ROT13Encoding.Append((char)C);
                        }
                    }
                    string HashedKey = UTF8Encoding.UTF8.GetString(MD5.Create().ComputeHash(UTF8Encoding.UTF8.GetBytes(ROT13Encoding.ToString())));
                    var GetTextToHEX = Encoding.Unicode.GetBytes(HashedKey);
                    var BuildHEX = new StringBuilder();
                    foreach (var FinalHEX in GetTextToHEX)
                    {
                        BuildHEX.Append(FinalHEX.ToString("X2"));
                    }
                    StringBuilder sb = new StringBuilder(); foreach (char c in BuildHEX.ToString().ToCharArray()) { sb.Append(Convert.ToString(c, 2).PadLeft(8, '0')); }
                    byte[] keys = MD5.Create().ComputeHash(UTF8Encoding.UTF8.GetBytes(sb.ToString()));
                    StringBuilder builder = new StringBuilder();
                    for (int i = 0; i < keys.Length; i++)
                    {
                        builder.Append(keys[i].ToString("x2"));
                    }
                    string DecryptedProgram = TqMIJUcgsXjVgxqJ(ProgramToDecrypt, builder.ToString(), IV);
                    byte[] ProgramToRun = Convert.FromBase64String(DecryptedProgram);
                    replacedembly RunInMemory = replacedembly.Load(ProgramToRun);
                    RunInMemory.EntryPoint.Invoke(null, null);
                }
            }
            catch(CryptographicException)
            {
                MessageBox.Show("Sorry But looks like you are not authorized to use this program.", "Error", MessageBoxButtons.OKCancel, MessageBoxIcon.Error);
            }
        }

19 View Source File : Main.cs
License : MIT License
Project Creator : AhmedMinegames

private void HWIDPacking(string FileToPack, string Output)
        {
            var Options = new Dictionary<string, string>();
            Options.Add("CompilerVersion", "v4.0");
            Options.Add("language", "c#");
            var codeProvider = new CSharpCodeProvider(Options);
            CompilerParameters parameters = new CompilerParameters();
            parameters.CompilerOptions = "/target:winexe";
            parameters.GenerateExecutable = true;
            parameters.Outputreplacedembly = Output;
            parameters.IncludeDebugInformation = false;
            string[] Librarys = { "System", "System.Windows.Forms", "System.Management", "System.Core", "System.Runtime", "System.Runtime.InteropServices" };
            foreach (string Library in Librarys)
            {
                parameters.Referencedreplacedemblies.Add(Library + ".dll");
            }
            byte[] CodeToProtect = File.ReadAllBytes(FileToPack);
            string RandomIV = RandomPreplacedword(16);
            string RandomKey = RandomPreplacedword(4);
            StringBuilder ROT13Encoding = new StringBuilder();
            Regex regex = new Regex("[A-Za-z]");
            foreach (char KSXZ in XOREncryptionKeys(textBox2.Text, RandomKey))
            {
                if (regex.IsMatch(KSXZ.ToString()))
                {
                    int C = ((KSXZ & 223) - 52) % 26 + (KSXZ & 32) + 65;
                    ROT13Encoding.Append((char)C);
                }
            }
            AesAlgorithms EncryptingBytes = new AesAlgorithms();
            string EncryptedKey = UTF8Encoding.UTF8.GetString(MD5.Create().ComputeHash(UTF8Encoding.UTF8.GetBytes(ROT13Encoding.ToString())));
            var GetTextToHEX = Encoding.Unicode.GetBytes(EncryptedKey);
            var BuildHEX = new StringBuilder();
            foreach (var FinalHEX in GetTextToHEX)
            {
                BuildHEX.Append(FinalHEX.ToString("X2"));
            }
            StringBuilder sb = new StringBuilder(); foreach (char c in BuildHEX.ToString().ToCharArray()) { sb.Append(Convert.ToString(c, 2).PadLeft(8, '0')); }
            byte[] keys = MD5.Create().ComputeHash(UTF8Encoding.UTF8.GetBytes(sb.ToString()));
            StringBuilder builder = new StringBuilder();
            for (int i = 0; i < keys.Length; i++)
            {
                builder.Append(keys[i].ToString("x2"));
            }
            string Final = EncryptingBytes.AesTextEncryption(Convert.ToBase64String(CodeToProtect), builder.ToString(), RandomIV);
            string HWIDPacker = Resource1.HWIDPacker;
            string NewHWIDPackerCode = HWIDPacker.Replace("DecME", Final).Replace("THISISIV", RandomIV).Replace("HWIDPacker", "namespace " + RandomName(14));
            string MyShinyNewPacker = NewHWIDPackerCode.Replace("SOS12", Convert.ToBase64String(Encoding.UTF8.GetBytes(RandomKey)));
            codeProvider.CompilereplacedemblyFromSource(parameters, MyShinyNewPacker);
        }

See More Examples