string.Insert(int, string)

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

724 Examples 7

19 View Source File : Entry.cs
License : MIT License
Project Creator : 0ffffffffh

public void FixForMultipleLineFeeds()
        {
            int index=0;

            while (index != -1)
            {
                index = Content.IndexOf("\r\n", index);

                if (index != -1)
                {
                    Content = Content.Remove(index, 2);

                    while (index + 2 < Content.Length)
                    {
                        if (Content.Substring(index, 2) == "\r\n")
                        {
                            Content = Content.Remove(index, 2).Insert(index, "<br/>");
                            index += 5;
                        }
                        else
                        {
                            Content = Content.Insert(index, "\r\n");
                            index += 2;
                            break;
                        }

                    }

                    if (index + 2 > Content.Length)
                        break;

                }
            }
        }

19 View Source File : CelesteNetChatComponent.cs
License : MIT License
Project Creator : 0x0ade

public void OnTextInput(char c) {
            if (!Active)
                return;

            if (c == (char) 13) {
                // Enter - send.
                // Handled in Update.

            } else if (c == (char) 8 && _CursorIndex > 0) {
                // Backspace - trim.
                if (Typing.Length > 0) {
                    int trim = 1;

                    // extra CursorIndex check since at index=1 using trim=1 is fine
                    if (_ControlHeld && _CursorIndex > 1) {
                        // adjust Ctrl+Backspace for having a space right before cursor
                        int _adjustedCursor = CursorIndex;
                        if (Typing[_CursorIndex - 1] == ' ')
                            _adjustedCursor--;
                        int prevWord = Typing.LastIndexOf(" ", _adjustedCursor - 1);
                        // if control is held and a space is found, trim from cursor back to space
                        if (prevWord >= 0)
                            trim = _adjustedCursor - prevWord;
                        // otherwise trim whole input back from cursor as it is one word
                        else
                            trim = _adjustedCursor;
                    }
                    // remove <trim> amount of characters before cursor
                    Typing = Typing.Remove(_CursorIndex - trim, trim);
                    _CursorIndex -= trim;
                }
                _RepeatIndex = 0;
                _Time = 0;
            } else if (c == (char) 127 && CursorIndex < Typing.Length) {
                // Delete - remove character after cursor.
                if (_ControlHeld && Typing[_CursorIndex] != ' ') {
                    int nextWord = Typing.IndexOf(" ", _CursorIndex);
                    // if control is held and a space is found, remove from cursor to space
                    if (nextWord >= 0) {
                        // include the found space in removal
                        nextWord++;
                        Typing = Typing.Remove(_CursorIndex, nextWord - _CursorIndex);
                    } else {
                        // otherwise remove everything after cursor
                        Typing = Typing.Substring(0, _CursorIndex);
                    }
                } else {
                    // just remove single char
                    Typing = Typing.Remove(_CursorIndex, 1);
                }
                _RepeatIndex = 0;
                _Time = 0;
            } else if (!char.IsControl(c)) {
                if (CursorIndex == Typing.Length) {
                    // Any other character - append.
                    Typing += c;
                } else {
                    // insert into string if cursor is not at the end
                    Typing = Typing.Insert(_CursorIndex, c.ToString());
                }
                _CursorIndex++;
                _RepeatIndex = 0;
                _Time = 0;
            }
        }

19 View Source File : FileWrite.cs
License : GNU General Public License v3.0
Project Creator : 0xthirteen

static void GetFileContent(string paylocation, string droploc, string fname, string dtype)
        {
            bool uricheck = Uri.IsWellFormedUriString(paylocation, UriKind.RelativeOrAbsolute);
            if (paylocation == "local")
            {
                String plfile = "LOADLOADLOAD";
                if(dtype == "flat")
                {
                    String finalpay = String.Format("Dim pLoad, fnames, droploc\npLoad =\"{0}\"\nfnames = \"{1}\"\ndroploc = \"{2}\"\n", plfile, fname, droploc);
                    vbsp = vbsp.Insert(0, finalpay);
                }
                else if (dtype == "nonflat")
                {
                    datavals = plfile;
                }
            }
            else
            {
                if (uricheck)
                {
                    try
                    {
                        WebClient webcl = new WebClient();
                        //May want to change this
                        webcl.Headers.Add("user-agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko");
                        byte[] filedata = webcl.DownloadData(paylocation);
                        string plfile = Convert.ToBase64String(filedata);
                        if (dtype == "flat")
                        {
                            String finalpay = String.Format("Dim pLoad, fnames, droploc\npLoad =\"{0}\"\nfnames = \"{1}\"\ndroploc = \"{2}\"\n", plfile, fname, droploc);
                            vbsp = vbsp.Insert(0, finalpay);
                        }
                        else if (dtype == "nonflat")
                        {
                            datavals = plfile;
                        }
                    }
                    catch (WebException)
                    {
                        Console.WriteLine("[X] URL doesnt exist");
                        return;
                    }
                }
                else
                {
                    try
                    {
                        Byte[] plbytes = File.ReadAllBytes(paylocation);
                        String plfile = Convert.ToBase64String(plbytes);
                        if(dtype == "flat")
                        {
                            String finalpay = String.Format("Dim pLoad, fnames, droploc\npLoad =\"{0}\"\nfnames = \"{1}\"\ndroploc = \"{2}\"\n", plfile, fname, droploc);
                            vbsp = vbsp.Insert(0, finalpay);
                        }
                        else if (dtype == "nonflat")
                        {
                            datavals = plfile;
                        }
                    }
                    catch (IOException)
                    {
                        Console.WriteLine("[X] File doesnt exist");
                        return;
                    }
                }
            }
        }

19 View Source File : MainWindow.xaml.cs
License : GNU General Public License v3.0
Project Creator : 1RedOne

private void TextBox_OnEndingButtonTextInput(object sender, TextCompositionEventArgs e)
        {
            var textBox = sender as TextBox;
            // Use SelectionStart property to find the caret position.
            // Insert the previewed text into the existing text in the textbox.
            var fullText = textBox.Text.Insert(textBox.SelectionStart, e.Text);

            double val;
            // If parsing is successful, set Handled to false
            e.Handled = !double.TryParse(fullText, out val);
        }

19 View Source File : ConditionTaskForm.cs
License : Apache License 2.0
Project Creator : 214175590

private void var_list_MouseClick(object sender, MouseEventArgs e)
        {
            isClickItem = true;
            var c = var_list.SelectedItems;
            if (c.Count > 0)
            {
                var_list.Visible = false;
                ListViewItem item = (ListViewItem)var_list.SelectedItems[0];
                if (null != item)
                {
                    string s = shell.Text;
                    string vars = item.Text;
                    int idx = shell.SkinTxt.SelectionStart;
                    s = s.Insert(idx, string.Format("{{{0}}}", vars));
                    shell.Text = s;
                    shell.SkinTxt.SelectionStart = idx + vars.Length + 2;
                    shell.SkinTxt.Focus();
                }
            }
        }

19 View Source File : MainWindow.xaml.cs
License : GNU General Public License v3.0
Project Creator : 1RedOne

private void TextBox_OnStartingButtonTextInput(object sender, TextCompositionEventArgs e)
        {
            var textBox = sender as TextBox;
            // Use SelectionStart property to find the caret position.
            // Insert the previewed text into the existing text in the textbox.
            var fullText = textBox.Text.Insert(textBox.SelectionStart, e.Text);

            double val;
            // If parsing is successful, set Handled to false
            e.Handled = !double.TryParse(fullText, out val);
        }

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

public static void NumberValidationTextBox(object sender, TextCompositionEventArgs e)
        {
            Regex regex = new Regex("^[.][0-9]+$|^[0-9]*[.]{0,1}[0-9]*$");
            e.Handled = !regex.IsMatch((sender as TextBox).Text.Insert((sender as TextBox).SelectionStart, e.Text));
        }

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

static void Main(string[] args)
        {
            printMenu();
            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
            if (args.Length < 1) {
                log("usage: xlsKami.exe [path/to/xls]", ConsoleColor.Red);
                return;
            }

            WorkbookEditor wbe;


            try {
                wbe = new WorkbookEditor(LoadDecoyDoreplacedent(args[0]));
            }
            catch (Exception e) {
                log(e.Message, ConsoleColor.Red);
                return;
            }
            
            for (bool bye = false; !bye; ) {
                try {
                    printMenu(showMenu: true, loadXlsPath: args[0]);
                    
                    switch (Convert.ToInt32(Console.ReadLine())) {

                        case 1:
                            log("[+] Enter Mode: Label Patching\n", ConsoleColor.Cyan);
                            wbe = cmd_ModifyLabel(wbe);
                            log("[+] Exit Mode\n", ConsoleColor.Cyan);
                            break;

                        case 2:
                            log("[+] Enter Mode: Sheet Patching\n", ConsoleColor.Cyan);
                            wbe = cmd_ModifySheet(wbe);
                            log("[!] Exit Mode\n", ConsoleColor.Cyan);
                            break;

                        case 3:
                            WorkbookStream createdWorkbook = wbe.WbStream;
                            ExcelDocWriter writer = new ExcelDocWriter();
                            string outputPath = args[0].Insert(args[0].LastIndexOf('.'), "_infect");
                            Console.WriteLine("Writing generated doreplacedent to {0}", outputPath);
                            writer.WriteDoreplacedent(outputPath, createdWorkbook, null);
                            bye = true;
                            break;

                        case 4:
                            bye = true;
                            break;


                    }
                }
                catch (Exception) { }
            }

            Console.WriteLine("Thanks for using xlsKami\nbye.\n");
        }

19 View Source File : PackageManifestUpdater.cs
License : Apache License 2.0
Project Creator : abist-co-ltd

internal static void EnsureMSBuildForUnity()
        {
            PackageManifest manifest = null;

            string manifestPath = GetPackageManifestFilePath();
            if (string.IsNullOrWhiteSpace(manifestPath))
            {
                return;
            }

            // Read the package manifest into a list of strings (for easy finding of entries)
            // and then deserialize.
            List<string> manifestFileLines = new List<string>();
            using (FileStream manifestStream = new FileStream(manifestPath, FileMode.Open, FileAccess.Read))
            {
                using (StreamReader reader = new StreamReader(manifestStream))
                {
                    // Read the manifest file a line at a time.
                    while (!reader.EndOfStream)
                    {
                        string line = reader.ReadLine();
                        manifestFileLines.Add(line);
                    }

                    // Go back to the start of the file.
                    manifestStream.Seek(0, 0);

                    // Deserialize the scoped registries portion of the package manifest.
                    manifest = JsonUtility.FromJson<PackageManifest>(reader.ReadToEnd());
                }
            }

            if (manifest == null)
            {
                Debug.LogError($"Failed to read the package manifest file ({manifestPath})");
                return;
            }

            // Ensure that pre-existing scoped registries are retained.
            List<ScopedRegistry> scopedRegistries = new List<ScopedRegistry>();
            if ((manifest.scopedRegistries != null) && (manifest.scopedRegistries.Length > 0))
            {
                scopedRegistries.AddRange(manifest.scopedRegistries);
            }

            // Attempt to find an entry in the scoped registries collection for the MSBuild for Unity URL
            bool needToAddRegistry = true;
            foreach (ScopedRegistry registry in scopedRegistries)
            {
                if (registry.url == MSBuildRegistryUrl)
                {
                    needToAddRegistry = false;
                }
            }

            // If no entry was found, add one.
            if (needToAddRegistry)
            {
                ScopedRegistry registry = new ScopedRegistry();
                registry.name = MSBuildRegistryName;
                registry.url = MSBuildRegistryUrl;
                registry.scopes = MSBuildRegistryScopes;

                scopedRegistries.Add(registry);
            }

            // Update the manifest's scoped registries, as the collection may have been modified.
            manifest.scopedRegistries = scopedRegistries.ToArray();

            int dependenciesStartIndex = -1;
            int scopedRegistriesStartIndex = -1;
            int scopedRegistriesEndIndex = -1;
            int packageLine = -1;

            // Presume that we need to add the MSBuild for Unity package. If this value is false,
            // we will check to see if the currently configured version meets or exceeds the
            // minimum requirements.
            bool needToAddPackage = true;

            // Attempt to find the MSBuild for Unity package entry in the dependencies collection
            // This loop also identifies the dependencies collection line and the start / end of a
            // pre-existing scoped registries collections
            for (int i = 0; i < manifestFileLines.Count; i++)
            {
                if (manifestFileLines[i].Contains("\"scopedRegistries\":"))
                {
                    scopedRegistriesStartIndex = i;
                }
                if (manifestFileLines[i].Contains("],") && (scopedRegistriesStartIndex != -1) && (scopedRegistriesEndIndex == -1))
                {
                    scopedRegistriesEndIndex = i;
                }
                if (manifestFileLines[i].Contains("\"dependencies\": {"))
                {
                    dependenciesStartIndex = i;
                }
                if (manifestFileLines[i].Contains(MSBuildPackageName))
                {
                    packageLine = i;
                    needToAddPackage = false;
                }
            }

            // If no package was found add it to the dependencies collection.
            if (needToAddPackage)
            {
                // Add the package to the collection (pad the entry with four spaces)
                manifestFileLines.Insert(dependenciesStartIndex + 1, $"    \"{MSBuildPackageName}\": \"{MSBuildPackageVersion}\",");
            }
            else
            {
                // Replace the line that currently exists
                manifestFileLines[packageLine] = $"    \"{MSBuildPackageName}\": \"{MSBuildPackageVersion}\",";
            }

            // Update the manifest file.
            // First, serialize the scoped registry collection.
            string serializedRegistriesJson = JsonUtility.ToJson(manifest, true);

            // Ensure that the file is truncated to ensure it is always valid after writing.
            using (FileStream outFile = new FileStream(manifestPath, FileMode.Truncate, FileAccess.Write))
            {
                using (StreamWriter writer = new StreamWriter(outFile))
                {
                    bool scopedRegistriesWritten = false;

                    // Write each line of the manifest back to the file.
                    for (int i = 0; i < manifestFileLines.Count; i++)
                    {
                        if ((i >= scopedRegistriesStartIndex) && (i <= scopedRegistriesEndIndex))
                        {
                            // Skip these lines, they will be replaced.
                            continue;
                        }

                        if (!scopedRegistriesWritten && (i > 0))
                        {
                            // Trim the leading '{' and '\n' from the serialized scoped registries
                            serializedRegistriesJson = serializedRegistriesJson.Remove(0, 2);
                            // Trim, the trailing '\n' and '}'
                            serializedRegistriesJson = serializedRegistriesJson.Remove(serializedRegistriesJson.Length - 2);
                            // Append a trailing ',' to close the scopedRegistries node
                            serializedRegistriesJson = serializedRegistriesJson.Insert(serializedRegistriesJson.Length, ",");
                            writer.WriteLine(serializedRegistriesJson);

                            scopedRegistriesWritten = true;
                        }

                        writer.WriteLine(manifestFileLines[i]);
                    }
                }
            }
        }

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

public void OnPostGenerateGradleAndroidProject(string path)
	{
		UnityEngine.Debug.Log("OVRGradleGeneration triggered.");

		var targetOculusPlatform = new List<string>();
		if (OVRDeviceSelector.isTargetDeviceQuest)
		{
			targetOculusPlatform.Add("quest");
		}
		OVRPlugin.AddCustomMetadata("target_oculus_platform", String.Join("_", targetOculusPlatform.ToArray()));
		UnityEngine.Debug.LogFormat("Quest = {0}", OVRDeviceSelector.isTargetDeviceQuest);

#if UNITY_2019_3_OR_NEWER
		string gradleBuildPath = Path.Combine(path, "../launcher/build.gradle");
#else
		string gradleBuildPath = Path.Combine(path, "build.gradle");
#endif
		bool v2SigningEnabled = true;

		if (File.Exists(gradleBuildPath))
		{
			try
			{
				string gradle = File.ReadAllText(gradleBuildPath);
				int v2Signingindex = gradle.IndexOf("v2SigningEnabled false");

				if (v2Signingindex != -1)
				{
					//v2 Signing flag found, ensure the correct value is set based on platform.
					if (v2SigningEnabled)
					{
						gradle = gradle.Replace("v2SigningEnabled false", "v2SigningEnabled true");
						System.IO.File.WriteAllText(gradleBuildPath, gradle);
					}
				}
				else
				{
					//v2 Signing flag missing, add it right after the key store preplacedword and set the value based on platform.
					int keyPreplacedIndex = gradle.IndexOf("keyPreplacedword");
					if (keyPreplacedIndex != -1)
					{
						int v2Index = gradle.IndexOf("\n", keyPreplacedIndex) + 1;
						if(v2Index != -1)
						{
							gradle = gradle.Insert(v2Index, "v2SigningEnabled " + (v2SigningEnabled ? "true" : "false") + "\n");
							System.IO.File.WriteAllText(gradleBuildPath, gradle);
						}
					}
				}
			}
			catch (System.Exception e)
			{
				UnityEngine.Debug.LogWarningFormat("Unable to overwrite build.gradle, error {0}", e.Message);
			}
		}
		else
		{
			UnityEngine.Debug.LogWarning("Unable to locate build.gradle");
		}

		PatchAndroidManifest(path);
	}

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

public void Write(string parsedSourceCode,
                          IList<Scope> scopes,
                          IStyleSheet styleSheet)
        {
            int offset = 0;
            bool lastScopeWasComment = false;

            foreach (Scope scope in scopes)
            {
                string t = parsedSourceCode.Substring(scope.Index, scope.Length);
//                    .Replace("\r\n", "\n")
//                    .Replace("\r", "\n");
                offset = scope.Index + scope.Length;
                if (!string.IsNullOrEmpty(t))
                {
                    if(scope.Name == "XML Attribute")
                    {
                        //Add space before attributes
                        t = t.Insert(0, " ");
                    }

                    Inline run = new Run { Text = t.Replace("\r",string.Empty) };
                    if (scope != null && styleSheet.Styles.Contains(scope.Name))
                    {
                        Style style = styleSheet.Styles[scope.Name];
                        run.Foreground = new SolidColorBrush(style.Foreground);
                    }
                    lastScopeWasComment = (scope != null && scope.Name == "Comment");
                    _text.Inlines.Add(run);
                }
            }
            string left = parsedSourceCode
                .Substring(offset)
                .Replace("\r\n", "\n")
                .Replace("\r", "\n");
            if (!string.IsNullOrEmpty(left))
            {
                for (int i = left.IndexOf("\n"); i >= 0; i = left.IndexOf("\n"))
                {
                    if (i > 0)
                    {
                        Inline tby = new Run { Text = left.Substring(0, i) };
                        _text.Inlines.Add(tby);
                    }

                    left = left.Substring(i + 1);
                    if (lastScopeWasComment)
                    {
                        lastScopeWasComment = false;
                    }
                    else
                    {
                        _text.Inlines.Add(new LineBreak());
                    }
                }

                if (!string.IsNullOrEmpty(left))
                {
                    Inline nrun = new Run { Text = left };
                    _text.Inlines.Add(nrun);
                }
            }
        }

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

public string HighlightTermsBase(string text, string[] terms)
        {
            var set = new HashSet<int>();
            foreach (var term in terms)
            {
                var indexes = text.ToLower().AllIndexesOf(term).Reverse().ToList();
                foreach (var index in indexes)
                {
                    for (int j = 0; j < term.Length; j++)
                    {
                        set.Add(j + index);
                    }
                }
            }

            if (set.Count > 0)
            {
                var list = set.ToList();
                list.Sort();

                var ranges = GetRanges(list.ToArray());
                ranges.Reverse();

                var color = HighlightColor ?? Colors.Black;
                string colorString = string.Format("#{0:X2}{1:X2}{2:X2}{3:X2}", color.A, color.R, color.G, color.B);

                foreach (var range in ranges)
                {
                    text = text.Insert(range.Item1 + range.Item2, "</Run>");
                    text = text.Insert(range.Item1, string.Format("<Run Foreground=\"{0}\">", colorString));
                }
            }

            return text;
        }

19 View Source File : BigDecimal.cs
License : MIT License
Project Creator : AdamWhiteHat

private static String ToString(BigInteger mantissa, int exponent, IFormatProvider provider)
		{
			if (provider == null) throw new ArgumentNullException();
			if (mantissa == null || BigDecimalNumberFormatInfo == null) { return NullString; }

			NumberFormatInfo formatProvider = NumberFormatInfo.GetInstance(provider);

			bool negativeValue = (mantissa.Sign == -1);
			bool negativeExponent = (Math.Sign(exponent) == -1);

			string result = BigInteger.Abs(mantissa).ToString();
			int absExp = Math.Abs(exponent);

			if (negativeExponent)
			{
				if (absExp > result.Length)
				{
					int zerosToAdd = Math.Abs(absExp - result.Length);
					string zeroString = string.Join(string.Empty, Enumerable.Repeat(formatProvider.NativeDigits[0], zerosToAdd));
					result = zeroString + result;
					result = result.Insert(0, formatProvider.NumberDecimalSeparator);
					result = result.Insert(0, formatProvider.NativeDigits[0]);
				}
				else
				{
					int indexOfRadixPoint = Math.Abs(absExp - result.Length);
					result = result.Insert(indexOfRadixPoint, formatProvider.NumberDecimalSeparator);
					if (indexOfRadixPoint == 0)
					{
						result = result.Insert(0, formatProvider.NativeDigits[0]);
					}
				}

				result = result.TrimEnd(new char[] { '0' });
				if (result.Last().ToString() == formatProvider.NumberDecimalSeparator)
				{
					result = result.Substring(0, result.Length - 1);
				}
			}
			else
			{
				string zeroString = string.Join(string.Empty, Enumerable.Repeat(formatProvider.NativeDigits[0], absExp));
				result += zeroString;
			}

			if (negativeExponent) // Prefix "0."
			{

			}
			if (negativeValue) // Prefix "-"
			{
				result = result.Insert(0, formatProvider.NegativeSign);
			}

			return result;


		}

19 View Source File : Serialization.Load.cs
License : GNU General Public License v3.0
Project Creator : AdamWhiteHat

private static string FixAppendedJsonArrays(string input)
            {
                //string inputJson = new string(input.Where(c => !char.IsWhiteSpace(c)).ToArray()); // Remove all whitespace
                //inputJson = inputJson.Replace("[", "").Replace("]", ""); // Remove square brackets. There may be many, due to multiple calls to Serialization.Save.Relations.Smooth.Append()
                //inputJson = inputJson.Replace("}{", "},{"); // Insert commas between item instances
                string inputJson = input.Insert(input.Length, "]").Insert(0, "["); // Re-add square brackets.
                return inputJson;
            }

19 View Source File : Serialization.Save.cs
License : GNU General Public License v3.0
Project Creator : AdamWhiteHat

public static void Append(GNFS gnfs, Relation relation)
                    {
                        if (relation != null && relation.IsSmooth && !relation.IsPersisted)
                        {
                            string filename = Path.Combine(gnfs.SaveLocations.SaveDirectory, $"{nameof(RelationContainer.SmoothRelations)}.json");
                            string json = JsonConvert.SerializeObject(relation, Formatting.Indented);

                            if (FileExists(gnfs))
                            {
                                json = json.Insert(0, ",");
                            }

                            File.AppendAllText(filename, json);

                            gnfs.CurrentRelationsProgress.SmoothRelationsCounter += 1;

                            relation.IsPersisted = true;
                        }
                    }

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

private string OpenGenericTypeName(ITypeSymbol type)
        {
            var genericTypeWithTypeParameters = type.ToString();

            var genOpenBraceIndex = genericTypeWithTypeParameters.IndexOf('<');
            var genCloseBraceIndex = genericTypeWithTypeParameters.LastIndexOf('>');

            var nts = (INamedTypeSymbol) type;
            var commas = new string(',', nts.TypeParameters.Length - 1);
            return genericTypeWithTypeParameters.Remove(genOpenBraceIndex + 1, genCloseBraceIndex - genOpenBraceIndex - 1).Insert(genOpenBraceIndex + 1, commas);
        }

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

private void ZPreplacedwordBox_TextChanged(object sender, System.Windows.Controls.TextChangedEventArgs e)
      {
         if (!this.mIsHandledTextChanged)
            return;

         foreach (TextChange c in e.Changes)
         {
            //从密码文中根据本次Change对象的索引和长度删除对应个数的字符
            this.Preplacedword = this.Preplacedword.Remove(c.Offset, c.RemovedLength);
            //将Text新增的部分记录给密码文
            this.Preplacedword = this.Preplacedword.Insert(c.Offset, Text.Substring(c.Offset, c.AddedLength));
         }

         if (!this.ShowPreplacedword)
         {
            this.SetText(ConvertToPreplacedwordChar(Text.Length));
         }

         //将光标放到最后面
         this.SelectionStart = this.Text.Length + 1;
      }

19 View Source File : AssertConsole.cs
License : GNU General Public License v3.0
Project Creator : agolaszewski

public void PositionWrite(string text, int x = 0, int y = 0, ConsoleColor color = ConsoleColor.White)
        {
            _currentY = y;
            if (!buffer.ContainsKey(y))
            {
                buffer.Add(y, string.Empty);
            }
            buffer[_currentY] = buffer[y].Insert(x, text);
        }

19 View Source File : AssertConsole.cs
License : GNU General Public License v3.0
Project Creator : agolaszewski

public void PositionWriteLine(string text, int x = 0, int y = 0, ConsoleColor color = ConsoleColor.White)
        {
            _currentY = y;
            if (!buffer.ContainsKey(y + 1))
            {
                buffer.Add(y + 1, string.Empty);
            }
            buffer[_currentY] = buffer[y + 1].Insert(x, text);
        }

19 View Source File : AssertConsole.cs
License : GNU General Public License v3.0
Project Creator : agolaszewski

public void Write(string text, ConsoleColor color = ConsoleColor.White)
        {
            if (!buffer.ContainsKey(_currentY))
            {
                buffer.Add(_currentY, string.Empty);
            }

            buffer[_currentY] = buffer[_currentY].Insert(0, text);
        }

19 View Source File : AssertConsole.cs
License : GNU General Public License v3.0
Project Creator : agolaszewski

public void WriteError(string error)
        {
            if (!buffer.ContainsKey(_currentY))
            {
                buffer.Add(_currentY, string.Empty);
            }
            buffer[_currentY] = buffer[_currentY].Insert(0, error);
        }

19 View Source File : AssertConsole.cs
License : GNU General Public License v3.0
Project Creator : agolaszewski

public void WriteLine(string text = " ", ConsoleColor color = ConsoleColor.White)
        {
            _currentY += 1;

            if (!buffer.ContainsKey(_currentY))
            {
                buffer.Add(_currentY, string.Empty);
            }

            buffer[_currentY] = buffer[_currentY].Insert(0, text);
        }

19 View Source File : Util.cs
License : MIT License
Project Creator : ajayyy

public static string FixupNewlines( string text )
		{
			bool newLinesRemaining = true;

			while ( newLinesRemaining )
			{
				int CIndex = text.IndexOf( "\\n" );

				if ( CIndex == -1 )
				{
					newLinesRemaining = false;
				}
				else
				{
					text = text.Remove( CIndex - 1, 3 );
					text = text.Insert( CIndex - 1, "\n" );
				}
			}

			return text;
		}

19 View Source File : ChineseIdCardNumberAttribute.cs
License : MIT License
Project Creator : albyho

private static bool CheckIDCard15(string id)
        {
            if (!long.TryParse(id, out var n) || n < Math.Pow(10, 14))
            {
                return false;//数字验证
            }

            if (AddressCode.IndexOf(id.Remove(2)) == -1)
            {
                return false;//省份验证
            }

            var birth = id.Substring(6, 6).Insert(4, "-").Insert(2, "-");
            if (!DateTime.TryParse(birth, out var _))
            {
                return false;//生日验证
            }

            return true;//符合15位身份证标准
        }

19 View Source File : ChineseIdCardNumberAttribute.cs
License : MIT License
Project Creator : albyho

private static bool CheckIDCard18(string id)
        {
            if (!long.TryParse(id.Remove(17), out var n) || n < Math.Pow(10, 16) || !long.TryParse(id.Replace('x', '0').Replace('X', '0'), out _))
            {
                return false;//数字验证
            }

            if (AddressCode.IndexOf(id.Remove(2)) == -1)
            {
                return false;//省份验证

            }
            var birth = id.Substring(6, 8).Insert(6, "-").Insert(4, "-");
            if (!DateTime.TryParse(birth, out _))
            {
                return false;//生日验证
            }

            var varifyCodes = ("1,0,x,9,8,7,6,5,4,3,2").Split(',');
            var wi = ("7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2").Split(',');
            var ai = id.Remove(17).ToCharArray();
            var sum = 0;
            for (var i = 0; i < 17; i++)
            {
                sum += int.Parse(wi[i]) * int.Parse(ai[i].ToString());
            }

            Math.DivRem(sum, 11, out int y);
            if (varifyCodes[y] != id.Substring(17, 1).ToLower())
            {
                return false;//校验码验证
            }

            return true;//符合GB11643-1999标准
        }

19 View Source File : Extension.cs
License : MIT License
Project Creator : AlenToma

public static string InsertBefore(this string str, string text, string identifier, bool insertLastIfNotFound = true)
        {
            var txt = "";
            var found = false;
            for (var j = str.Length - 1; j >= 0; j--)
            {
                txt = str[j] + txt;
                if (txt == identifier)
                {
                    str = str.Insert(j, text);
                    found = true;
                    break;
                }
                else if (txt.Length >= identifier.Length || txt.Last() != identifier.Last() || (txt.Length >= 2 && identifier.Length >= 2 && txt[txt.Length - 2] != identifier[identifier.Length - 2]))
                    txt = "";
            }
            if (!found && insertLastIfNotFound)
                str += text;

            return str;
        }

19 View Source File : MethodHelper.cs
License : MIT License
Project Creator : AlenToma

internal static ISqlCommand ProcessSql(this IRepository repository, TransactionSqlConnection connection, IDbTransaction tran, string sql)
        {
            var i = 1;
            var dicCols = new SafeValueType<string, Tuple<object, SqlDbType>>();
            MatchCollection matches = null;
            while ((matches = stringExp.Matches(sql)).Count > 0)
            {
                var exp = matches[0];
                var col = "@CO" + i + "L";
                object str = exp.Value.TrimEnd(']').Substring(@"String\[".Length - 1);
                sql = sql.Remove(exp.Index, exp.Value.Length);
                sql = sql.Insert(exp.Index, col);
                var v = str.ConvertValue<string>();
                if (string.Equals(v, "null", StringComparison.OrdinalIgnoreCase))
                    v = null;
                dicCols.TryAdd(col, new Tuple<object, SqlDbType>(v, SqlDbType.NVarChar));
                i++;
            }

            while ((matches = dateExp.Matches(sql)).Count > 0)
            {
                var exp = matches[0];
                var col = "@CO" + i + "L";
                object str = exp.Value.TrimEnd(']').Substring(@"Date\[".Length - 1);
                sql = sql.Remove(exp.Index, exp.Value.Length);
                sql = sql.Insert(exp.Index, col);
                dicCols.TryAdd(col, new Tuple<object, SqlDbType>(str.ConvertValue<DateTime?>(), SqlDbType.DateTime));
                i++;
            }

            while ((matches = guidExp.Matches(sql)).Count > 0)
            {
                var exp = matches[0];
                var col = "@CO" + i + "L";
                object str = exp.Value.TrimEnd(']').Substring(@"Guid\[".Length - 1);
                sql = sql.Remove(exp.Index, exp.Value.Length);
                sql = sql.Insert(exp.Index, col);
                dicCols.TryAdd(col, new Tuple<object, SqlDbType>(str.ConvertValue<Guid?>(), SqlDbType.UniqueIdentifier));
                i++;
            }


            while ((matches = decimalExp.Matches(sql)).Count > 0)
            {
                var exp = matches[0];
                var col = "@CO" + i + "L";
                object str = exp.Value.TrimEnd(']').Substring(@"Decimal\[".Length - 1);
                sql = sql.Remove(exp.Index, exp.Value.Length);
                sql = sql.Insert(exp.Index, col);
                dicCols.TryAdd(col, new Tuple<object, SqlDbType>(str.ConvertValue<decimal?>(), SqlDbType.Decimal));
                i++;
            }

            sql = sql.CleanValidSqlName(repository.DataBaseTypes);
            DbCommand cmd = null;

            try
            {
                switch (repository.DataBaseTypes)
                {
                    case DataBaseTypes.Mssql:
                        cmd = tran != null ?
                            "System.Data.SqlClient.SqlCommand".GetObjectType("System.Data.SqlClient").CreateInstance(new object[] { sql, connection.DBConnection, tran }) as DbCommand :
                                  "System.Data.SqlClient.SqlCommand".GetObjectType("System.Data.SqlClient").CreateInstance(new object[] { sql, connection.DBConnection }) as DbCommand;
                        break;

                    case DataBaseTypes.PostgreSql:
                        cmd = tran != null ?
                           "Npgsql.NpgsqlCommand".GetObjectType("Npgsql").CreateInstance(new object[] { sql, connection.DBConnection, tran }) as DbCommand :
                                 "Npgsql.NpgsqlCommand".GetObjectType("Npgsql").CreateInstance(new object[] { sql, connection.DBConnection }) as DbCommand;
                        break;

                    case DataBaseTypes.Sqllight:
                        cmd = tran != null ?
                             "System.Data.SQLite.SQLiteCommand".GetObjectType("System.Data.SQLite").CreateInstance(new object[] { sql, connection.DBConnection, tran }) as DbCommand :
                                   "System.Data.SQLite.SQLiteCommand".GetObjectType("System.Data.SQLite").CreateInstance(new object[] { sql, connection.DBConnection }) as DbCommand;
                        break;
                }
            }
            catch (Exception e)
            {
                switch (repository.DataBaseTypes)
                {
                    case DataBaseTypes.Mssql:
                        throw new EnreplacedyException($"Please make sure that nuget 'System.Data.SqlClient' is installed \n orginal exception: \n {e.Message}");

                    case DataBaseTypes.PostgreSql:
                        throw new EnreplacedyException($"Please make sure that nuget 'Npgsql' is installed \n orginal exception: \n {e.Message}");

                    case DataBaseTypes.Sqllight:
                        throw new EnreplacedyException($"Please make sure that nuget 'System.Data.SQLite' is installed \n orginal exception: \n {e.Message}");
                }
            }

            var dbCommandExtended = new DbCommandExtended(cmd, repository);
            foreach (var dic in dicCols)
            {
                dbCommandExtended.AddInnerParameter(dic.Key, dic.Value.Item1);

            }
            return dbCommandExtended;
        }

19 View Source File : Extension.cs
License : MIT License
Project Creator : AlenToma

public static string InsertAfter(this string str, string text, string identifier, bool insertLastIfNotFound = true)
        {
            var txt = "";
            var found = false;
            for (var j = str.Length - 1; j >= 0; j--)
            {
                txt = str[j] + txt;
                if (txt == identifier)
                {
                    str = str.Insert(j, text);
                    found = true;
                    break;
                }
                else if (txt.Length >= identifier.Length || txt.Last() != identifier.Last() || (txt.Length >= 2 && identifier.Length >= 2 && txt[txt.Length - 2] != identifier[identifier.Length - 2]))
                    txt = "";
            }

            if (!found && insertLastIfNotFound)
                str += text;
            return str;
        }

19 View Source File : NumericTextBox.cs
License : MIT License
Project Creator : AlexGyver

protected override void WndProc(ref Message m)
		{
			// Switch to handle message...
			switch (m.Msg)
			{
				case WM_PASTE:
					{
						// Get clipboard object to paste
						IDataObject clipboardData = Clipboard.GetDataObject();

						// Get text from clipboard data
						string pasteText = (string)clipboardData.GetData(
								DataFormats.UnicodeText);

						// Get the number of characters to replace
						int selectionLength = SelectionLength;

						// If no replacement or insertion, we are done
						if (pasteText.Length == 0)
						{
							break;
						}
						else if (selectionLength != 0)
						{
							base.Text = base.Text.Remove(SelectionStart, selectionLength);
						}

						bool containsInvalidChars = false;
						foreach (char c in pasteText)
						{
							if (containsInvalidChars)
							{
								break;
							}
							else if (invalidNumeric(c))
							{
								containsInvalidChars = true;
							}
						}

						if (!containsInvalidChars)
						{
							base.Text = base.Text.Insert(SelectionStart, pasteText);
						}

						return;
					}

			}
			base.WndProc(ref m);
		}

19 View Source File : TemplateMultiPass.cs
License : MIT License
Project Creator : alexismorin

void LoadTemplateBody( string guid )
		{
			m_preplacedUniqueIdData.Clear();
			m_guid = guid;
			string datapath = replacedetDatabase.GUIDToreplacedetPath( guid );
			string shaderBody = string.Empty;
			shaderBody = IOUtils.LoadTextFileFromDisk( datapath );
			shaderBody = shaderBody.Replace( "\r\n", "\n" );

			// Insert Before Tag
			MatchCollection col = Regex.Matches( shaderBody, TemplateHelperFunctions.BeforePragmaPattern, RegexOptions.Singleline );
			for( int i = col.Count - 1; i >= 0; i-- )
			{
				if( col[ i ].Groups.Count == 3 )
				{
					shaderBody = shaderBody.Insert( col[ i ].Groups[ 2 ].Index, TemplatesManager.TemplatePragmaBeforeTag + "\n" + col[ i ].Groups[ 1 ].Value );
				}
			}

			m_shaderData = TemplateShaderInfoUtil.CreateShaderData( shaderBody );
			if( m_shaderData == null )
			{
				m_isValid = false;
				return;
			}

			m_templateIdManager = new TemplateIdManager( shaderBody );

			try
			{
				int nameBegin = shaderBody.IndexOf( TemplatesManager.TemplateShaderNameBeginTag );
				if( nameBegin < 0 )
				{
					// Not a template
					return;
				}

				int nameEnd = shaderBody.IndexOf( TemplatesManager.TemplateFullEndTag, nameBegin );
				if( nameEnd < 0 )
					return;

				
				m_shaderBody = shaderBody;
				int defaultBegin = nameBegin + TemplatesManager.TemplateShaderNameBeginTag.Length;
				int defaultLength = nameEnd - defaultBegin;
				m_defaultShaderName = shaderBody.Substring( defaultBegin, defaultLength );
				int[] nameIdx = m_defaultShaderName.AllIndexesOf( "\"" );
				nameIdx[ 0 ] += 1; // Ignore the " character from the string
				m_defaultShaderName = m_defaultShaderName.Substring( nameIdx[ 0 ], nameIdx[ 1 ] - nameIdx[ 0 ] );
				m_shaderNameId = shaderBody.Substring( nameBegin, nameEnd + TemplatesManager.TemplateFullEndTag.Length - nameBegin );
				m_templateProperties.AddId( shaderBody, m_shaderNameId, false );
				m_templateIdManager.RegisterId( nameBegin, m_shaderNameId, m_shaderNameId );
				shaderBody = shaderBody.Substring( nameEnd + TemplatesManager.TemplateFullEndTag.Length );
			}
			catch( Exception e )
			{
				Debug.LogException( e );
				m_isValid = false;
			}

			m_customTemplatePropertyUI = TemplateHelperFunctions.FetchCustomUI( shaderBody );
			TemplateHelperFunctions.FetchDependencies( m_dependenciesContainer, ref m_shaderBody );
			if( m_dependenciesContainer.IsValid )
			{
				int index = m_dependenciesContainer.Id.IndexOf( TemplatesManager.TemplateDependenciesListTag );
				m_templateProperties.AddId( new TemplateProperty( m_dependenciesContainer.Id, m_dependenciesContainer.Id.Substring( 0, index ), true ) );
				m_templateIdManager.RegisterId( m_dependenciesContainer.Index, m_dependenciesContainer.Id, m_dependenciesContainer.Id );
			}

			TemplateHelperFunctions.FetchCustomInspector( m_customInspectorContainer, ref m_shaderBody );
			if( m_customInspectorContainer.IsValid )
			{
				int index = m_customInspectorContainer.Id.IndexOf( "CustomEditor" );
				m_templateProperties.AddId( new TemplateProperty( m_customInspectorContainer.Id, m_customInspectorContainer.Id.Substring( 0, index ), true ) );
				m_templateIdManager.RegisterId( m_customInspectorContainer.Index, m_customInspectorContainer.Id, m_customInspectorContainer.Id );
			}

			TemplateHelperFunctions.FetchFallback( m_fallbackContainer, ref m_shaderBody );
			if( m_fallbackContainer.IsValid )
			{
				int index = m_fallbackContainer.Id.IndexOf( "Fallback",StringComparison.InvariantCultureIgnoreCase );
				m_templateProperties.AddId( new TemplateProperty( m_fallbackContainer.Id, m_fallbackContainer.Id.Substring( 0, index ), true ) );
				m_templateIdManager.RegisterId( m_fallbackContainer.Index, m_fallbackContainer.Id, m_fallbackContainer.Id );
			}
			// Shader body may have been changed to inject inexisting tags like fallback
			m_templateIdManager.ShaderBody = m_shaderBody;

			m_propertyTag = new TemplateTagData( m_shaderData.PropertyStartIdx, TemplatesManager.TemplatePropertyTag, true );
			m_templateIdManager.RegisterId( m_shaderData.PropertyStartIdx, TemplatesManager.TemplatePropertyTag, TemplatesManager.TemplatePropertyTag );
			m_templateProperties.AddId( shaderBody, TemplatesManager.TemplatePropertyTag, true );
			Dictionary<string, TemplateShaderPropertyData> duplicatesHelper = new Dictionary<string, TemplateShaderPropertyData>();
			TemplateHelperFunctions.CreateShaderPropertiesList( m_shaderData.Properties, ref m_availableShaderProperties, ref duplicatesHelper );
			int subShaderCount = m_shaderData.SubShaders.Count;

			int mainSubShaderIdx = -1;
			int mainPreplacedIdx = -1;

			int firstVisibleSubShaderId = -1;
			int firstVisiblePreplacedId = -1;
			bool foundMainPreplaced = false;
			bool foundFirstVisible = false;

			m_templateIdManager.RegisterTag( TemplatesManager.TemplatePreplacedesEndTag );
			m_templateIdManager.RegisterTag( TemplatesManager.TemplateMainPreplacedTag );

			for( int i = 0; i < subShaderCount; i++ )
			{
				TemplateSubShader subShader = new TemplateSubShader( i, m_templateIdManager, "SubShader" + i, m_shaderData.SubShaders[ i ], ref duplicatesHelper );

				if( subShader.FoundMainPreplaced )
				{
					if( !foundMainPreplaced )
					{
						foundMainPreplaced = true;
						mainSubShaderIdx = i;
						mainPreplacedIdx = subShader.MainPreplaced;
					}
				}
				else if( subShader.MainPreplaced > -1 )
				{
					if( !foundFirstVisible )
					{
						foundFirstVisible = true;
						firstVisibleSubShaderId = i;
						firstVisiblePreplacedId = subShader.MainPreplaced;
					}
				}

				m_subShaders.Add( subShader );
				m_masterNodesRequired += subShader.Preplacedes.Count;
			}


			if( !foundMainPreplaced && foundFirstVisible )
			{
				mainSubShaderIdx = firstVisibleSubShaderId;
				mainPreplacedIdx = firstVisiblePreplacedId;
			}

			for( int subShaderIdx = 0; subShaderIdx < subShaderCount; subShaderIdx++ )
			{
				int preplacedCount = m_subShaders[ subShaderIdx ].Preplacedes.Count;
				for( int preplacedIdx = 0; preplacedIdx < preplacedCount; preplacedIdx++ )
				{
					m_subShaders[ subShaderIdx ].Preplacedes[ preplacedIdx ].IsMainPreplaced = ( mainSubShaderIdx == subShaderIdx && mainPreplacedIdx == preplacedIdx );
				}
			}

			duplicatesHelper.Clear();
			duplicatesHelper = null;
			m_isSinglePreplaced = ( m_subShaders.Count == 1 && m_subShaders[ 0 ].PreplacedAmount == 1 );
			
		}

19 View Source File : TemplateData.cs
License : MIT License
Project Creator : alexismorin

void FetchSubShaderProperties()
		{
			Match match = Regex.Match( m_templateBody, @"Preplaced\s*{" );
			if( match.Groups.Count == 0 )
			{
				return;
			}

			int beginSubShader = m_templateBody.IndexOf( "SubShader" );
			int endSubShader = match.Groups[ 0 ].Index;
			if( beginSubShader > 0 && endSubShader > 0 && endSubShader > beginSubShader )
			{
				// ADD A PLACE TO INSERT GRAB PreplacedES
				int preplacedIndex = m_templateBody.IndexOf( TemplatesManager.TemplatePreplacedTag );
				if( preplacedIndex < 0 )
				{
					int currIdx = endSubShader - 1;
					string identation = string.Empty;
					for( ; currIdx > 0; currIdx-- )
					{
						if( m_templateBody[ currIdx ] != '\n' )
						{
							identation = m_templateBody[ currIdx ] + identation;
						}
						else
						{
							identation = m_templateBody[ currIdx ] + identation;
							break;
						}
					}
					if( currIdx > 0 )
					{
						m_templateBody = m_templateBody.Insert( currIdx, identation + TemplatesManager.TemplatePreplacedTag );
					}
				}

				// GET ALL THE MODULES
				string subBody = m_templateBody.Substring( beginSubShader, endSubShader - beginSubShader );
				//CULL MODE
				{
					int cullIdx = subBody.IndexOf( "Cull" );
					if( cullIdx > 0 )
					{
						int end = subBody.IndexOf( TemplatesManager.TemplateNewLine, cullIdx );
						string cullParams = subBody.Substring( cullIdx, end - cullIdx );
						m_cullModeData.CullModeId = cullParams;
						TemplateHelperFunctions.CreateCullMode( cullParams, ref m_cullModeData );
						if( m_cullModeData.DataCheck == TemplateDataCheck.Valid )
							AddId( cullParams, false, string.Empty );
					}
				}
				//COLOR MASK
				{
					int colorMaskIdx = subBody.IndexOf( "ColorMask" );
					if( colorMaskIdx > 0 )
					{
						int end = subBody.IndexOf( TemplatesManager.TemplateNewLine, colorMaskIdx );
						string colorMaskParams = subBody.Substring( colorMaskIdx, end - colorMaskIdx );
						m_colorMaskData.ColorMaskId = colorMaskParams;
						TemplateHelperFunctions.CreateColorMask( colorMaskParams, ref m_colorMaskData );
						if( m_colorMaskData.DataCheck == TemplateDataCheck.Valid )
							AddId( colorMaskParams, false );
					}
				}
				//BlEND MODE
				{
					int blendModeIdx = subBody.IndexOf( "Blend" );
					if( blendModeIdx > 0 )
					{
						int end = subBody.IndexOf( TemplatesManager.TemplateNewLine, blendModeIdx );
						string blendParams = subBody.Substring( blendModeIdx, end - blendModeIdx );
						m_blendData.BlendModeId = blendParams;
						TemplateHelperFunctions.CreateBlendMode( blendParams, ref m_blendData );
						if( m_blendData.ValidBlendMode )
						{
							AddId( blendParams, false );
						}
					}
				}
				//BLEND OP
				{
					int blendOpIdx = subBody.IndexOf( "BlendOp" );
					if( blendOpIdx > 0 )
					{
						int end = subBody.IndexOf( TemplatesManager.TemplateNewLine, blendOpIdx );
						string blendOpParams = subBody.Substring( blendOpIdx, end - blendOpIdx );
						BlendData.BlendOpId = blendOpParams;
						TemplateHelperFunctions.CreateBlendOp( blendOpParams, ref m_blendData );
						if( m_blendData.ValidBlendOp )
						{
							AddId( blendOpParams, false );
						}
					}

					m_blendData.DataCheck = ( m_blendData.ValidBlendMode || m_blendData.ValidBlendOp ) ? TemplateDataCheck.Valid : TemplateDataCheck.Invalid;
				}

				//STENCIL
				{
					int stencilIdx = subBody.IndexOf( "Stencil" );
					if( stencilIdx > -1 )
					{
						int stencilEndIdx = subBody.IndexOf( "}", stencilIdx );
						if( stencilEndIdx > 0 )
						{
							string stencilParams = subBody.Substring( stencilIdx, stencilEndIdx + 1 - stencilIdx );
							m_stencilData.StencilBufferId = stencilParams;
							TemplateHelperFunctions.CreateStencilOps( stencilParams, ref m_stencilData );
							if( m_stencilData.DataCheck == TemplateDataCheck.Valid )
							{
								AddId( stencilParams, true );
							}
						}
					}
				}

				//ZWRITE
				{
					int zWriteOpIdx = subBody.IndexOf( "ZWrite" );
					if( zWriteOpIdx > -1 )
					{
						int zWriteEndIdx = subBody.IndexOf( TemplatesManager.TemplateNewLine, zWriteOpIdx );
						if( zWriteEndIdx > 0 )
						{
							m_depthData.ZWriteModeId = subBody.Substring( zWriteOpIdx, zWriteEndIdx + 1 - zWriteOpIdx );
							TemplateHelperFunctions.CreateZWriteMode( m_depthData.ZWriteModeId, ref m_depthData );
							if( m_depthData.DataCheck == TemplateDataCheck.Valid )
							{
								AddId( m_depthData.ZWriteModeId, true );
							}
						}
					}
				}

				//ZTEST
				{
					int zTestOpIdx = subBody.IndexOf( "ZTest" );
					if( zTestOpIdx > -1 )
					{
						int zTestEndIdx = subBody.IndexOf( TemplatesManager.TemplateNewLine, zTestOpIdx );
						if( zTestEndIdx > 0 )
						{
							m_depthData.ZTestModeId = subBody.Substring( zTestOpIdx, zTestEndIdx + 1 - zTestOpIdx );
							TemplateHelperFunctions.CreateZTestMode( m_depthData.ZTestModeId, ref m_depthData );
							if( m_depthData.DataCheck == TemplateDataCheck.Valid )
							{
								AddId( m_depthData.ZTestModeId, true );
							}
						}
					}
				}

				//ZOFFSET
				{
					int zOffsetIdx = subBody.IndexOf( "Offset" );
					if( zOffsetIdx > -1 )
					{
						int zOffsetEndIdx = subBody.IndexOf( TemplatesManager.TemplateNewLine, zOffsetIdx );
						if( zOffsetEndIdx > 0 )
						{
							m_depthData.OffsetId = subBody.Substring( zOffsetIdx, zOffsetEndIdx + 1 - zOffsetIdx );
							TemplateHelperFunctions.CreateZOffsetMode( m_depthData.OffsetId, ref m_depthData );
							if( m_depthData.DataCheck == TemplateDataCheck.Valid )
							{
								AddId( m_depthData.OffsetId, true );
							}
						}
					}

					m_depthData.SetDataCheck(); 
				}
				
				//TAGS
				{
					int tagsIdx = subBody.IndexOf( "Tags" );
					if( tagsIdx > -1 )
					{
						int tagsEndIdx = subBody.IndexOf( "}", tagsIdx );
						if( tagsEndIdx > -1 )
						{
							m_tagData.Reset();
							m_tagData.TagsId = subBody.Substring( tagsIdx, tagsEndIdx + 1 - tagsIdx );
							TemplateHelperFunctions.CreateTags( ref m_tagData, true );
							m_tagData.DataCheck = TemplateDataCheck.Valid;
							AddId( m_tagData.TagsId, false );
						}
						else
						{
							m_tagData.DataCheck = TemplateDataCheck.Invalid;
						}
					}
					else
					{
						m_tagData.DataCheck = TemplateDataCheck.Invalid;
					}
				}
			}
		}

19 View Source File : TemplateData.cs
License : GNU General Public License v3.0
Project Creator : alexismorin

void FetchSubShaderProperties()
		{
			Match match = Regex.Match( m_templateBody, @"Preplaced\s*{" );
			if( match.Groups.Count == 0 )
			{
				return;
			}

			int beginSubShader = m_templateBody.IndexOf( "SubShader" );
			int endSubShader = match.Groups[ 0 ].Index;
			if( beginSubShader > 0 && endSubShader > 0 && endSubShader > beginSubShader )
			{
				// ADD A PLACE TO INSERT GRAB PreplacedES
				int preplacedIndex = m_templateBody.IndexOf( TemplatesManager.TemplatePreplacedTag );
				if( preplacedIndex < 0 )
				{
					int currIdx = endSubShader - 1;
					string identation = string.Empty;
					for( ; currIdx > 0; currIdx-- )
					{
						if( m_templateBody[ currIdx ] != '\n' )
						{
							identation = m_templateBody[ currIdx ] + identation;
						}
						else
						{
							identation = m_templateBody[ currIdx ] + identation;
							break;
						}
					}
					if( currIdx > 0 )
					{
						m_templateBody = m_templateBody.Insert( currIdx, identation + TemplatesManager.TemplatePreplacedTag );
					}
				}

				// GET ALL THE MODULES
				string subBody = m_templateBody.Substring( beginSubShader, endSubShader - beginSubShader );
				//CULL MODE
				{
					int cullIdx = subBody.IndexOf( "Cull" );
					if( cullIdx > 0 )
					{
						int end = subBody.IndexOf( TemplatesManager.TemplateNewLine, cullIdx );
						string cullParams = subBody.Substring( cullIdx, end - cullIdx );
						m_cullModeData.CullModeId = cullParams;
						TemplateHelperFunctions.CreateCullMode( cullParams, ref m_cullModeData );
						if( m_cullModeData.DataCheck == TemplateDataCheck.Valid )
							AddId( cullParams, false, string.Empty );
					}
				}
				//COLOR MASK
				{
					int colorMaskIdx = subBody.IndexOf( "ColorMask" );
					if( colorMaskIdx > 0 )
					{
						int end = subBody.IndexOf( TemplatesManager.TemplateNewLine, colorMaskIdx );
						string colorMaskParams = subBody.Substring( colorMaskIdx, end - colorMaskIdx );
						m_colorMaskData.ColorMaskId = colorMaskParams;
						TemplateHelperFunctions.CreateColorMask( colorMaskParams, ref m_colorMaskData );
						if( m_colorMaskData.DataCheck == TemplateDataCheck.Valid )
							AddId( colorMaskParams, false );
					}
				}
				//BlEND MODE
				{
					int blendModeIdx = subBody.IndexOf( "Blend" );
					if( blendModeIdx > 0 )
					{
						int end = subBody.IndexOf( TemplatesManager.TemplateNewLine, blendModeIdx );
						string blendParams = subBody.Substring( blendModeIdx, end - blendModeIdx );
						m_blendData.BlendModeId = blendParams;
						TemplateHelperFunctions.CreateBlendMode( blendParams, ref m_blendData );
						if( m_blendData.ValidBlendMode )
						{
							AddId( blendParams, false );
						}
					}
				}
				//BLEND OP
				{
					int blendOpIdx = subBody.IndexOf( "BlendOp" );
					if( blendOpIdx > 0 )
					{
						int end = subBody.IndexOf( TemplatesManager.TemplateNewLine, blendOpIdx );
						string blendOpParams = subBody.Substring( blendOpIdx, end - blendOpIdx );
						BlendData.BlendOpId = blendOpParams;
						TemplateHelperFunctions.CreateBlendOp( blendOpParams, ref m_blendData );
						if( m_blendData.ValidBlendOp )
						{
							AddId( blendOpParams, false );
						}
					}

					m_blendData.DataCheck = ( m_blendData.ValidBlendMode || m_blendData.ValidBlendOp ) ? TemplateDataCheck.Valid : TemplateDataCheck.Invalid;
				}

				//STENCIL
				{
					int stencilIdx = subBody.IndexOf( "Stencil" );
					if( stencilIdx > -1 )
					{
						int stencilEndIdx = subBody.IndexOf( "}", stencilIdx );
						if( stencilEndIdx > 0 )
						{
							string stencilParams = subBody.Substring( stencilIdx, stencilEndIdx + 1 - stencilIdx );
							m_stencilData.StencilBufferId = stencilParams;
							TemplateHelperFunctions.CreateStencilOps( stencilParams, ref m_stencilData );
							if( m_stencilData.DataCheck == TemplateDataCheck.Valid )
							{
								AddId( stencilParams, true );
							}
						}
					}
				}

				//ZWRITE
				{
					int zWriteOpIdx = subBody.IndexOf( "ZWrite" );
					if( zWriteOpIdx > -1 )
					{
						int zWriteEndIdx = subBody.IndexOf( TemplatesManager.TemplateNewLine, zWriteOpIdx );
						if( zWriteEndIdx > 0 )
						{
							m_depthData.ZWriteModeId = subBody.Substring( zWriteOpIdx, zWriteEndIdx + 1 - zWriteOpIdx );
							TemplateHelperFunctions.CreateZWriteMode( m_depthData.ZWriteModeId, ref m_depthData );
							if( m_depthData.DataCheck == TemplateDataCheck.Valid )
							{
								AddId( m_depthData.ZWriteModeId, true );
							}
						}
					}
				}

				//ZTEST
				{
					int zTestOpIdx = subBody.IndexOf( "ZTest" );
					if( zTestOpIdx > -1 )
					{
						int zTestEndIdx = subBody.IndexOf( TemplatesManager.TemplateNewLine, zTestOpIdx );
						if( zTestEndIdx > 0 )
						{
							m_depthData.ZTestModeId = subBody.Substring( zTestOpIdx, zTestEndIdx + 1 - zTestOpIdx );
							TemplateHelperFunctions.CreateZTestMode( m_depthData.ZTestModeId, ref m_depthData );
							if( m_depthData.DataCheck == TemplateDataCheck.Valid )
							{
								AddId( m_depthData.ZTestModeId, true );
							}
						}
					}
				}

				//ZOFFSET
				{
					int zOffsetIdx = subBody.IndexOf( "Offset" );
					if( zOffsetIdx > -1 )
					{
						int zOffsetEndIdx = subBody.IndexOf( TemplatesManager.TemplateNewLine, zOffsetIdx );
						if( zOffsetEndIdx > 0 )
						{
							m_depthData.OffsetId = subBody.Substring( zOffsetIdx, zOffsetEndIdx + 1 - zOffsetIdx );
							TemplateHelperFunctions.CreateZOffsetMode( m_depthData.OffsetId, ref m_depthData );
							if( m_depthData.DataCheck == TemplateDataCheck.Valid )
							{
								AddId( m_depthData.OffsetId, true );
							}
						}
					}
				}

				//TAGS
				{
					int tagsIdx = subBody.IndexOf( "Tags" );
					if( tagsIdx > -1 )
					{
						int tagsEndIdx = subBody.IndexOf( "}", tagsIdx );
						if( tagsEndIdx > -1 )
						{
							m_tagData.Reset();
							m_tagData.TagsId = subBody.Substring( tagsIdx, tagsEndIdx + 1 - tagsIdx );
							TemplateHelperFunctions.CreateTags( ref m_tagData, true );
							m_tagData.DataCheck = TemplateDataCheck.Valid;
							AddId( m_tagData.TagsId, false );
						}
						else
						{
							m_tagData.DataCheck = TemplateDataCheck.Invalid;
						}
					}
					else
					{
						m_tagData.DataCheck = TemplateDataCheck.Invalid;
					}
				}
			}
		}

19 View Source File : StringExtensions.cs
License : MIT License
Project Creator : AlFasGD

public static string Replace(this string originalString, string stringToReplaceWith, int startIndex, int length)
        {
            string result = originalString;
            result = result.Remove(startIndex, length);
            result = result.Insert(startIndex, stringToReplaceWith);
            return result;
        }

19 View Source File : Database.cs
License : MIT License
Project Creator : AlFasGD

public void ImportLevel(string level, bool initializeLoading = true)
        {
            for (int i = UserLevelCount - 1; i >= 0; i--) // Increase the level indices of all the other levels to insert the cloned level at the start
                RawDecryptedLevelDataString = RawDecryptedLevelDataString.Replace($"<k>k_{i}</k>", $"<k>k_{i + 1}</k>");
            level = RemoveLevelIndexKey(level); // Remove the index key of the level
            RawDecryptedLevelDataString = RawDecryptedLevelDataString.Insert(LevelKeyStartIndices[0] - 10, $"<k>k_0</k>{level}"); // Insert the new level
            int clonedLevelLength = level.Length + 10; // The length of the inserted level
            LevelKeyStartIndices = LevelKeyStartIndices.InsertAtStart(LevelKeyStartIndices[0]); // Add the new key start position in the array
            for (int i = 1; i < LevelKeyStartIndices.Count; i++)
                LevelKeyStartIndices[i] += clonedLevelLength; // Increase the other key indices by the length of the cloned level
            // Insert the imported level and initialize its replacedysis
            var newLevel = new Level(level);
            if (initializeLoading)
                newLevel.InitializeLoadingLevelString();
            UserLevels.Insert(0, newLevel);
        }

19 View Source File : HttpLogServiceClientBuilder.cs
License : MIT License
Project Creator : aliyun

private Uri parseUri(String endpoint, String project)
        {
            Uri uri;
            if (endpoint.StartsWith("http://"))
            {
                uri = new UriBuilder(endpoint.Insert(7, project + ".")).Uri;
            } else if (endpoint.StartsWith("https://"))
            {
                uri = new UriBuilder(endpoint.Insert(8, project + ".")).Uri;
            } else
            {
                uri = new UriBuilder("http://" + project + "." + endpoint).Uri;
            }

            return uri;
        }

19 View Source File : ExtensionMethods.cs
License : MIT License
Project Creator : Altevir

public static string TransformNumberToString(this int number)
        {
            switch (number.ToString().Length)
            {
                case 1:
                case 2:
                case 3:
                    return number.ToString();
                case 4:
                    return $"{number.ToString().Insert(1, ",").Substring(0, 3)}k";
                case 5:
                    return $"{number.ToString().Insert(2, ",").Substring(0, 4)}k";
                case 6:
                    return $"{number.ToString().Insert(3, ",").Substring(0, 5)}k";
                default:
                    return $"{number.ToString().Insert(1, ",").Substring(0, 3)}m";
            }
        }

19 View Source File : UpdateChecker.cs
License : MIT License
Project Creator : AmazingDM

public static async Task UpdateNetch(DownloadProgressChangedEventHandler onDownloadProgressChanged)
        {
            using WebClient client = new();

            var latestVersionDownloadUrl = LatestRelease.replacedets[0].browser_download_url;
            var tagPage = await client.DownloadStringTaskAsync(LatestVersionUrl);
            var match = Regex.Match(tagPage, @"<td .*>(?<sha256>.*)</td>", RegexOptions.Singleline);

            // TODO Replace with regex get basename and sha256 
            var fileName = Path.GetFileName(new Uri(latestVersionDownloadUrl).LocalPath);
            fileName = fileName.Insert(fileName.LastIndexOf('.'), LatestVersionNumber);
            var fileFullPath = Path.Combine(Global.NetchDir, "data", fileName);

            var sha256 = match.Groups["sha256"].Value;

            if (File.Exists(fileFullPath))
            {
                if (Utils.Utils.SHA256CheckSum(fileFullPath) == sha256)
                {
                    RunUpdater();
                    return;
                }

                File.Delete(fileFullPath);
            }

            try
            {
                client.DownloadProgressChanged += onDownloadProgressChanged;
                await client.DownloadFileTaskAsync(new Uri(latestVersionDownloadUrl), fileFullPath);
                client.DownloadProgressChanged -= onDownloadProgressChanged;
            }
            catch (Exception e)
            {
                throw new Exception(i18N.Translate("Download Update Failed", ": ") + e.Message);
            }

            if (Utils.Utils.SHA256CheckSum(fileFullPath) != sha256)
                throw new Exception(i18N.Translate("The downloaded file has the wrong hash"));

            RunUpdater();

            void RunUpdater()
            {
                // if debugging process stopped, debugger will kill child processes!!!!
                // 调试进程结束,调试器将会杀死子进程
                // uncomment if(!Debugger.isAttach) block in NetchUpdater Project's main() method and attach to NetchUpdater process to debug
                // 在 NetchUpdater 项目的  main() 方法中取消注释 if(!Debugger.isAttach)块,并附加到 NetchUpdater 进程进行调试
                Process.Start(new ProcessStartInfo
                {
                    FileName = Path.Combine(Global.NetchDir, "NetchUpdater.exe"),
                    Arguments =
                        $"{Global.Settings.UDPSocketPort} \"{fileFullPath}\" \"{Global.NetchDir}\""
                });
            }
        }

19 View Source File : NgItemWizard.cs
License : MIT License
Project Creator : andfomin

private bool ModifyStartupCsFile(string projectDirectory)
        {
            var filePath = Path.Combine(projectDirectory, NgWizardHelper.StartupCsFileName);
            if (!File.Exists(filePath))
            {
                return false;
            }

            var codeLines = File.ReadAllLines(filePath);
            var methodHeaderLine = codeLines
            .Where(i => i.Contains("public void") && i.Contains("Configure") && i.Contains("IApplicationBuilder") && i.Contains("IHostingEnvironment"))
            .FirstOrDefault()
            ;

            if (String.IsNullOrEmpty(methodHeaderLine))
            {
                return false;
            }

            var appPattern = @"(?:IApplicationBuilder)\s+(\w+(?=\)|,|\s))";
            var appVariableName = FindMatch(methodHeaderLine, appPattern);
            var envPattern = @"(?:IHostingEnvironment)\s+(\w+(?=\)|,|\s))";
            var envVariableName = FindMatch(methodHeaderLine, envPattern);

            if (String.IsNullOrEmpty(appVariableName) || String.IsNullOrEmpty(envVariableName))
            {
                return false;
            }

            var codeText = File.ReadAllText(filePath);

            var methodStartPos = codeText.IndexOf(methodHeaderLine);

            // MVC and WebAPI projects already have UseStaticFiles() inserted by their templates.
            var useStaticFilesPos = codeText.IndexOf($"{appVariableName}.UseStaticFiles", methodStartPos);
            var useFileServerPos = codeText.IndexOf($"{appVariableName}.UseFileServer", methodStartPos);
            var insertUseStaticFiles = (useStaticFilesPos == -1) && (useFileServerPos == -1);

            /* The position of the snippet affects the routing in the project. Middleware handlers are called in the order of registration.
             * We serve at "/" in Empty and WebAPI, at "/ng/" in MVC and Razor Pages.
             * WebAPI, MVC and Razor Pages have routing, we serve everything else (including 404 at dev time). 
             * We hijack processing in the Empty project (it has a hardcoded response in app.Run()). 
             */
            int insertPos = codeText.IndexOf($"{appVariableName}.Run(", methodStartPos);
            if (insertPos == -1)
            {
                insertPos = FindEndOfMethod(codeText, methodStartPos);
            }
            if (insertPos > 0)
            {
                insertPos = RewindWhitespaces(codeText, insertPos);

                var ngSnippet = LineBreak +
                    "#region /* Added by the Angular CLI template. --- BEGIN --- */" + LineBreak +
                    $"if ({envVariableName}.IsDevelopment())" + LineBreak +
                    "{" + LineBreak +
                    $"{appVariableName}.UseWebSockets().UseNgProxy();" + LineBreak +
                    "}" + LineBreak +
                    "else" + LineBreak +
                    "{" + LineBreak;
                if (insertUseStaticFiles)
                {
                    ngSnippet = ngSnippet +
                        $"{appVariableName}.UseStaticFiles();" + LineBreak;
                }
                ngSnippet = ngSnippet +
                    $"{appVariableName}.UseNgRoute();" + LineBreak +
                    "}" + LineBreak +
                    "#endregion /* Added by the Angular CLI template. --- END --- */" + LineBreak + LineBreak;

                codeText = codeText.Insert(insertPos, ngSnippet);

                File.WriteAllText(filePath, codeText);

                return true;
            }

            return false;
        }

19 View Source File : Utils.cs
License : MIT License
Project Creator : AndyFilter

public static String CleanLatex(string Latex)
        {
            var LatexArray = Latex.ToList();
            String clean = "";
            //for (int i = 0; i < LatexArray.Count; i++)
            //{
            //    if (Latex[i] == '\\' && Latex[i + 1] == '\\')
            //    {
            //        clean = Latex.Remove(i, 2).Insert(i, "\\");
            //    }
            //    else if (Latex[i] == '\\' && Latex[i + 1] == ' ' && Latex[i + 2] == '\\')
            //    {
            //        clean = Latex.Remove(i, 3).Insert(i, "\\");
            //    }
            //    else if (Latex[i] == '\\' && Latex[i + 1] == '\\')
            //    {
            //        clean = Latex.Remove(i, 2).Insert(i, "v");
            //    }
            //}
            //clean = Regex.Replace(Latex, @"\\ \\", @"\");

            for (int i = 0; i < LatexArray.Count; i++)
            {
                if (Latex[i] == '\\' && Latex[i + 1] != '\\')
                {
                    Latex = Latex.Remove(i, 2).Insert(i, string.Format(@"\{0}", Latex[i + 1]));
                }
            }

            clean = Latex.Replace(@"\\", @"\").Replace(@"\ ", "%^&").Replace("%^& %^&", @" \ ").Replace("%^&", "").Replace(@"\ ", @"\,");
            return clean;
        }

19 View Source File : Dialog.cs
License : MIT License
Project Creator : AngeloCresta

private void YValue_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
		{
			if((e.KeyChar >= '0' && e.KeyChar <= '9') || e.KeyChar == 8 || e.KeyChar == 46  || e.KeyChar == '.')
			{
				string editText = ((TextBox)(sender)).Text;
				if(e.KeyChar != 8)
				{
					TextBox textBox = (TextBox)sender;
					int selStart = textBox.SelectionStart;
					int selLength = textBox.SelectionLength;
	
					if(selLength > 0)
					{
						editText = editText.Remove(selStart, selLength);
						textBox.Text = editText;
						textBox.SelectionLength = 0;
						textBox.SelectionStart = selStart;
					}


					editText = editText.Insert(selStart,e.KeyChar.ToString());

					try
					{
						double newValue = double.Parse(editText);
						if(newValue <= 10 && newValue >= 0)
						{
							e.Handled = false;
						}
						else
							e.Handled = true;
					}
					catch(Exception )
					{
						e.Handled = true;
					}
				}
				else
					e.Handled = false;
			}
			else
			{
				e.Handled = true;
			}
		
		}

19 View Source File : ChatPage.xaml.cs
License : MIT License
Project Creator : angelsix

private void MessageText_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            // Get the text box
            var textbox = sender as TextBox;

            // Check if we have pressed enter
            if (e.Key == Key.Enter)
            {
                // If we have control pressed...
                if (Keyboard.Modifiers.HasFlag(ModifierKeys.Control))
                {
                    // Add a new line at the point where the cursor is
                    var index = textbox.CaretIndex;

                    // Insert the new line
                    textbox.Text = textbox.Text.Insert(index, Environment.NewLine);

                    // Shift the caret forward to the newline
                    textbox.CaretIndex = index + Environment.NewLine.Length;

                    // Mark this key as handled by us
                    e.Handled = true;
                }
                else
                    // Send the message
                    ViewModel.Send();

                // Mark the key as handled
                e.Handled = true;
            }
        }

19 View Source File : ValueConverter.cs
License : MIT License
Project Creator : AngeloCresta

public static string FormatValue(
			Chart chart,
			object obj,
            object objTag,
			double value, 
			string format, 
			ChartValueType valueType,
			ChartElementType elementType)
		{
            format = format ?? String.Empty;
            string	convertionFormat = format;
			string	result = "";

			// Make sure value index is part of the format
			if(convertionFormat != null && convertionFormat.Length > 0)
			{
				int	bracketIndex = convertionFormat.IndexOf('{', 0);
				if(bracketIndex >= 0)
				{
					while(bracketIndex >= 0)
					{
						// If format is not followed by the value index
						if(!convertionFormat.Substring(bracketIndex).StartsWith("{0:", StringComparison.Ordinal))
						{
							// Check charcter prior to the bracket
							if(bracketIndex >= 1 && convertionFormat.Substring(bracketIndex - 1, 1) == "{")
							{
								continue;
							}
							else
							{
								// Insert value index in format
								convertionFormat = convertionFormat.Insert(bracketIndex + 1, "0:");
							}
						}

						bracketIndex = convertionFormat.IndexOf('{', bracketIndex + 1);
					}
				}
				else
				{
					convertionFormat = "{0:" + convertionFormat + "}";
				}
			}

			// Date/time formating
            if (valueType == ChartValueType.DateTime || 
                valueType == ChartValueType.DateTimeOffset || 
                valueType == ChartValueType.Date)
			{
				// Set default format
				if(convertionFormat.Length == 0)
				{
					convertionFormat = "{0:d}";
                    if (valueType == ChartValueType.DateTimeOffset)
                        convertionFormat += " +0";
				}

				// Convert date to string
                result = String.Format(CultureInfo.CurrentCulture, convertionFormat, DateTime.FromOADate(value));
			}
			else if(valueType == ChartValueType.Time)
			{
				// Set default format
				if(convertionFormat.Length == 0)
				{
					convertionFormat = "{0:t}";
				}

				// Convert date to string
                result = String.Format(CultureInfo.CurrentCulture, convertionFormat, DateTime.FromOADate(value));
			}
			else
			{
				bool	failedFlag = false;

				// Set default format
				if(convertionFormat.Length == 0)
				{
					convertionFormat = "{0:G}";
				}

				try
				{
					// Numeric value formatting
                    result = String.Format(CultureInfo.CurrentCulture,convertionFormat, value);
				}
				catch(FormatException)
				{
					failedFlag = true;
				}

				// If numeric formatting failed try to format using decimal number
				if(failedFlag)
				{
					failedFlag = false;
                    try
                    {
                        // Decimal value formatting
                        result = String.Format(CultureInfo.CurrentCulture, convertionFormat, (long)value);
                    }
                    catch (ArgumentNullException)
                    {
                        failedFlag = true;
                    }
                    catch (FormatException)
                    {
                        failedFlag = true;
                    }
				}

				// Return format string as result (literal) if all formatting methods failed
				if(failedFlag)
				{
                    result = format;
				}
			}

            // For the Reporting Services chart a special number formatting
            // handler may be set and used for all formatting needs.
            if (chart != null)
            {
                // Call number formatter
                FormatNumberEventArgs eventArguments = new FormatNumberEventArgs(value, format, valueType, result, objTag, elementType);
                chart.CallOnFormatNumber(obj, eventArguments);
                result = eventArguments.LocalizedValue;
            }

			return result;
		}

19 View Source File : Utils.cs
License : Apache License 2.0
Project Creator : anpShawn

public static string FormatBigInt(long inBig, bool inAllowFontDownsize=true, int inDownsizeAmt = 5)
    {
        //under 1000, return verbatim
        if (inBig < 1000) return inBig.ToString();

        //build a string that consists of the number's first x digits with a decimal point inserted
        builder.Length = 0;
        string strBig = inBig.ToString();
        int numDigits = strBig.Length;
        int divisionsBy3 = numDigits / 3;
        int modulusBy3 = numDigits % 3;

        int digitsToCapture = modulusBy3 + 1;
        if (modulusBy3 == 0) digitsToCapture = 4;
        string temp = strBig.Substring(0, digitsToCapture);
        temp = temp.Insert(temp.Length-1, ".");

        builder.Append(temp);
        bool lastDigitIsZero = temp[temp.Length-1] == '0';

        //over 1 decillion? return as scientific notation
        if (numDigits > 36)
        {
            builder.Append(" ");
            if(inAllowFontDownsize)builder.Append($"<size=-{inDownsizeAmt}>");
            builder.Append("e");
            builder.Append(numDigits - 1);
            if(inAllowFontDownsize)builder.Append("</size>");
        }
        else
        {
            //if the last digit is a 0, remove it AND the preceding decimal point
            if(lastDigitIsZero)
            {
                builder.Remove(builder.Length-2, 2);
            }

            //then append a custom symbol
            int notationIndex = modulusBy3 == 0 ? divisionsBy3 - 1 : divisionsBy3;
            notationIndex--; //decrement to base it on a zero-indexed array of characters
            builder.Append(" ");
            if(inAllowFontDownsize)builder.Append($"<size=-{inDownsizeAmt}>");
            builder.Append( notationSymbols[notationIndex] );
            if(inAllowFontDownsize)builder.Append("</size>");
        }

        return builder.ToString();

        /*Examples
         * 
         * 5
         * 10
         * 250
         * 1k               4 digits (3 places to move)
         * 1.3k
         * 10k
         * 100k
         * 1M               7 digits (6 places to move)
         * 1.6M
         * 20M
         * 500M
         * 1B
         * 10B
         * 345B
         * 1T
         * 
         * K, M, B, T
         * q quadrillion
         * Q quintillion
         * s Sextillion
         * S Septillion
         * O Octillion
         * N Nonillion
         * d Decillion       34 digits (33 places to move)
         * 
         * 
         * 1 eXX
         * */
    }

19 View Source File : UTF8String.cs
License : GNU General Public License v3.0
Project Creator : anydream

public UTF8String Insert(int startIndex, string value) {
			return new UTF8String(String.Insert(startIndex, value));
		}

19 View Source File : AnsiColorTerminalAppender.cs
License : Apache License 2.0
Project Creator : apache

protected override void Append(log4net.Core.LoggingEvent loggingEvent) 
		{
			string loggingMessage = RenderLoggingEvent(loggingEvent);

			// see if there is a specified lookup.
			LevelColors levelColors = m_levelMapping.Lookup(loggingEvent.Level) as LevelColors;
			if (levelColors != null)
			{
				// Prepend the Ansi Color code
				loggingMessage = levelColors.CombinedColor + loggingMessage;
			}

			// on most terminals there are weird effects if we don't clear the background color
			// before the new line.  This checks to see if it ends with a newline, and if
			// so, inserts the clear codes before the newline, otherwise the clear codes
			// are inserted afterwards.
			if (loggingMessage.Length > 1)
			{
				if (loggingMessage.EndsWith("\r\n") || loggingMessage.EndsWith("\n\r")) 
				{
					loggingMessage = loggingMessage.Insert(loggingMessage.Length - 2, PostEventCodes);
				} 
				else if (loggingMessage.EndsWith("\n") || loggingMessage.EndsWith("\r")) 
				{
					loggingMessage = loggingMessage.Insert(loggingMessage.Length - 1, PostEventCodes);
				} 
				else 
				{
					loggingMessage = loggingMessage + PostEventCodes;
				}
			}
			else
			{
				if (loggingMessage[0] == '\n' || loggingMessage[0] == '\r') 
				{
					loggingMessage = PostEventCodes + loggingMessage;
				} 
				else 
				{
					loggingMessage = loggingMessage + PostEventCodes;
				}
			}

#if NETCF_1_0
			// Write to the output stream
			Console.Write(loggingMessage);
#else
			if (m_writeToErrorStream)
			{
				// Write to the error stream
				Console.Error.Write(loggingMessage);
			}
			else
			{
				// Write to the output stream
				Console.Write(loggingMessage);
			}
#endif
		
		}

19 View Source File : Textbox.cs
License : MIT License
Project Creator : Apostolique

public override void UpdateInput(GameTime gameTime) {
            if (Clip.Contains(GuiHelper.Mouse) && Default.MouseInteraction.Pressed()) {
                _pressed = true;
                Cursor = MouseToCursor(GuiHelper.Mouse.X, _text);
                GrabFocus(this);
            }

            if (IsFocused) {
                if (_pressed && Default.MouseInteraction.HeldOnly()) {
                    Cursor = MouseToCursor(GuiHelper.Mouse.X, _text);
                }
                if (_pressed && Default.MouseInteraction.Released()) {
                    _pressed = false;
                    Cursor = MouseToCursor(GuiHelper.Mouse.X, _text);
                }

                MoveCursor(Default.MoveLeft, -1);
                MoveCursor(Default.MoveRight, 1);

                if (Default.MoveUp.Released()) {
                    Cursor = 0;
                }
                if (Default.MoveDown.Released()) {
                    Cursor = _text.Length;
                }

                foreach (var te in InputHelper.TextEvents) {
                    if (te.Key == Keys.Tab) {
                        continue;
                    } else if (te.Key == Keys.Enter) {
                    } else if (te.Key == Keys.Back) {
                        if (Cursor > 0 && _text.Length > 0) {
                            Cursor--;
                            Text = _text.Remove(Cursor, 1);
                        }
                    } else if (te.Key == Keys.Delete) {
                        if (_text.Length > 0 && Cursor < _text.Length) {
                            Text = _text.Remove(Cursor, 1);
                            _cursorBlink = _cursorBlinkSpeed;
                        }
                    } else {
                        Text = _text.Insert(Cursor, $"{te.Character}");
                        Cursor++;
                    }
                    Track.KeyboardCondition.Consume(te.Key);
                }
            }
        }

19 View Source File : ConvertUtil.cs
License : Apache License 2.0
Project Creator : Appdynamics

internal static void ExcelEncodeString(StreamWriter sw, string t)
        {
            if (Regex.IsMatch(t, "(_x[0-9A-F]{4,4}_)"))
            {
                var match = Regex.Match(t, "(_x[0-9A-F]{4,4}_)");
                int indexAdd = 0;
                while (match.Success)
                {
                    t = t.Insert(match.Index + indexAdd, "_x005F");
                    indexAdd += 6;
                    match = match.NextMatch();
                }
            }
            for (int i = 0; i < t.Length; i++)
            {
                if (t[i] <= 0x1f && t[i] != '\t' && t[i] != '\n' && t[i] != '\r') //Not Tab, CR or LF
                {
                    sw.Write("_x00{0}_", (t[i] < 0xf ? "0" : "") + ((int)t[i]).ToString("X"));
                }
                else
                {
                    sw.Write(t[i]);
                }
            }

        }

19 View Source File : ConvertUtil.cs
License : Apache License 2.0
Project Creator : Appdynamics

internal static void ExcelEncodeString(StringBuilder sb, string t, bool encodeTabCRLF=false)
        {
            if (Regex.IsMatch(t, "(_x[0-9A-F]{4,4}_)"))
            {
                var match = Regex.Match(t, "(_x[0-9A-F]{4,4}_)");
                int indexAdd = 0;
                while (match.Success)
                {
                    t = t.Insert(match.Index + indexAdd, "_x005F");
                    indexAdd += 6;
                    match = match.NextMatch();
                }
            }
            for (int i = 0; i < t.Length; i++)
            {
                if (t[i] <= 0x1f && ((t[i] != '\t' && t[i] != '\n' && t[i] != '\r' && encodeTabCRLF == false) || encodeTabCRLF)) //Not Tab, CR or LF
                {
                    sb.AppendFormat("_x00{0}_", (t[i] < 0xf ? "0" : "") + ((int)t[i]).ToString("X"));
                }
                else
                {
                    sb.Append(t[i]);
                }
            }

        }

19 View Source File : SysMenuAppService.cs
License : MIT License
Project Creator : aprilyush

private string GetMenuNamePre(int level)
        {
            string pre = "";
            for(int i = 0; i < level; i++)
            {
                pre += "¦┄┄";
            }
            return pre.Insert(0," ");
        }

19 View Source File : SaveToArasCmd.cs
License : MIT License
Project Creator : arasplm

public override void ExecuteCommandImpl(object sender, EventArgs args)
		{
			var project = projectManager.SelectedProject;

			string selectedMethodPath = projectManager.MethodPath;
			string sourceCode = File.ReadAllText(selectedMethodPath, new UTF8Encoding(true));
			string selectedMethodName = Path.GetFileNameWithoutExtension(selectedMethodPath);

			string projectConfigPath = projectManager.ProjectConfigPath;

			MethodInfo methodInformation = projectConfigurationManager.CurrentProjectConfiguraiton.MethodInfos.FirstOrDefault(m => m.MethodName == selectedMethodName);
			if (methodInformation == null)
			{
				throw new Exception();
			}

			string packageMethodFolderPath = this.projectConfigurationManager.CurrentProjectConfiguraiton.UseCommonProjectStructure ? methodInformation.Package.MethodFolderPath : string.Empty;
			string methodWorkingFolder = Path.Combine(projectManager.ServerMethodFolderPath, packageMethodFolderPath, methodInformation.MethodName);

			ICodeProvider codeProvider = codeProviderFactory.GetCodeProvider(projectManager.Language);

			CodeInfo codeItemInfo = codeProvider.UpdateSourceCodeToInsertExternalItems(methodWorkingFolder, sourceCode, methodInformation, projectConfigurationManager.CurrentProjectConfiguraiton.UseVSFormatting);
			if (codeItemInfo != null)
			{
				var dialogResult = dialogFactory.GetMessageBoxWindow().ShowDialog(messageManager.GetMessage("CouldNotInsertExternalItemsInsideOfMethodCodeSection"),
					messageManager.GetMessage("ArasVSMethodPlugin"),
					MessageButtons.OKCancel,
					MessageIcon.Question);
				if (dialogResult == MessageDialogResult.Cancel)
				{
					return;
				}

				projectManager.AddItemTemplateToProjectNew(codeItemInfo, packageMethodFolderPath, true, 0);
				sourceCode = codeItemInfo.Code;
			}

			string methodCode = codeProvider.LoadMethodCode(methodWorkingFolder, sourceCode);

			var packageManager = new PackageManager(authManager, this.messageManager);
			var saveView = dialogFactory.GetSaveToArasView(projectConfigurationManager, packageManager, methodInformation, methodCode, projectConfigPath, project.Name, project.FullName);
			var saveViewResult = saveView.ShowDialog();
			if (saveViewResult?.DialogOperationResult != true)
			{
				return;
			}

			TemplateLoader templateLoader = new TemplateLoader();
			templateLoader.Load(projectManager.MethodConfigPath);

			dynamic currentMethodItem = saveViewResult.MethodItem;

			if (!currentMethodItem.isError())
			{
				methodCode = saveViewResult.MethodCode;
				var template = templateLoader.Templates.FirstOrDefault(t => t.TemplateName == saveViewResult.TemplateName);
				if (template != null && !template.IsSupported)
				{
					if (!methodCode.Contains(string.Format("//MethodTemplateName={0}", template.TemplateName)))
					{
						methodCode = methodCode.Insert(0, string.Format("//MethodTemplateName={0};\r\n", template.TemplateName));
					}
				}

				currentMethodItem.setProperty("comments", saveViewResult.MethodComment);
				currentMethodItem.setProperty("method_code", methodCode);
				currentMethodItem.setProperty("name", saveViewResult.MethodName);
				currentMethodItem.setProperty("method_type", saveViewResult.MethodLanguage);
				currentMethodItem.setProperty("execution_allowed_to", saveViewResult.SelectedIdenreplacedyId);

				var action = GetUpdateAction(currentMethodItem.getLockStatus());
				currentMethodItem = currentMethodItem.apply(action);
			}
			else
			{
				methodCode = saveViewResult.MethodCode;
				var template = templateLoader.Templates.FirstOrDefault(t => t.TemplateName == saveViewResult.TemplateName);
				if (template != null && !template.IsSupported)
				{
					if (!methodCode.Contains(string.Format("//MethodTemplateName={0}", template.TemplateName)))
					{
						methodCode = methodCode.Insert(0, string.Format("//MethodTemplateName={0};\r\n", template.TemplateName));
					}
				}

				currentMethodItem = authManager.InnovatorInstance.newItem("Method", "add");
				currentMethodItem.setProperty("comments", saveViewResult.MethodComment);
				currentMethodItem.setProperty("method_code", methodCode);
				currentMethodItem.setProperty("name", saveViewResult.MethodName);
				currentMethodItem.setProperty("method_type", saveViewResult.MethodLanguage);
				currentMethodItem.setProperty("execution_allowed_to", saveViewResult.SelectedIdenreplacedyId);
				currentMethodItem = currentMethodItem.apply();
			}

			if (currentMethodItem.isError())
			{
				throw new Exception(currentMethodItem.getErrorString());
			}

			string newId = currentMethodItem.getID();
			string configId = currentMethodItem.getProperty("config_id");

			if (string.IsNullOrEmpty(saveViewResult.CurrentMethodPackage))
			{
				packageManager.AddPackageElementToPackageDefinition(configId, saveViewResult.MethodName, saveViewResult.SelectedPackageInfo.Name);
			}
			else
			{
				if (!string.Equals(saveViewResult.CurrentMethodPackage, saveViewResult.SelectedPackageInfo.ToString()))
				{
					packageManager.DeletePackageByElementIdFromPackageDefinition(configId);
					packageManager.AddPackageElementToPackageDefinition(configId, saveViewResult.MethodName, saveViewResult.SelectedPackageInfo.Name);
				}
			}

			if (methodInformation.MethodName == saveViewResult.MethodName &&
				methodInformation.Package.Name == saveViewResult.SelectedPackageInfo.Name)
			{
				methodInformation.InnovatorMethodConfigId = configId;
				methodInformation.InnovatorMethodId = newId;
				methodInformation.Package = saveViewResult.SelectedPackageInfo;
				methodInformation.ExecutionAllowedToKeyedName = saveViewResult.SelectedIdenreplacedyKeyedName;
				methodInformation.ExecutionAllowedToId = saveViewResult.SelectedIdenreplacedyId;
				methodInformation.MethodComment = saveViewResult.MethodComment;

				projectConfigurationManager.Save(projectConfigPath);
			}

			var messageBoxWindow = dialogFactory.GetMessageBoxWindow();
			messageBoxWindow.ShowDialog(this.messageManager.GetMessage("MethodSaved", saveViewResult.MethodName),
				string.Empty,
				MessageButtons.OK,
				MessageIcon.Information);
		}

See More Examples