System.Text.RegularExpressions.Regex.IsMatch(string)

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

2100 Examples 7

19 Source : SqlInjectionChecker.cs
with MIT License
from 0x1000000

public static bool CheckTSqlBuildInFunctionName(string name)
        {
            return tSqlFunctionName.IsMatch(name);
        }

19 Source : JitDasmOptions.cs
with MIT License
from 0xd4d

public bool IsMatch(string value) {
			foreach (var regex in regexes) {
				if (regex.IsMatch(value))
					return true;
			}
			return false;
		}

19 Source : Program.cs
with MIT License
from 2401dem

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

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

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

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

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

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

19 Source : TemplateEngin.cs
with MIT License
from 2881099

private static string htmlSyntax(string tplcode, int num) {

			while (num-- > 0) {
				string[] arr = _reg_syntax.Split(tplcode);

				if (arr.Length == 1) break;
				for (int a = 1; a < arr.Length; a += 4) {
					string tag = string.Concat('<', arr[a]);
					string end = string.Concat("</", arr[a], '>');
					int fc = 1;
					for (int b = a; fc > 0 && b < arr.Length; b += 4) {
						if (b > a && arr[a].ToLower() == arr[b].ToLower()) fc++;
						int bpos = 0;
						while (true) {
							int fa = arr[b + 3].IndexOf(tag, bpos);
							int fb = arr[b + 3].IndexOf(end, bpos);
							if (b == a) {
								var z = arr[b + 3].IndexOf("/>");
								if ((fb == -1 || z < fb) && z != -1) {
									var y = arr[b + 3].Substring(0, z + 2);
									if (_reg_htmltag.IsMatch(y) == false)
										fb = z - end.Length + 2;
								}
							}
							if (fa == -1 && fb == -1) break;
							if (fa != -1 && (fa < fb || fb == -1)) {
								fc++;
								bpos = fa + tag.Length;
								continue;
							}
							if (fb != -1) fc--;
							if (fc <= 0) {
								var a1 = arr[a + 1];
								var end3 = string.Concat("{/", a1, "}");
								if (a1.ToLower() == "else") {
									if (_reg_blank.Replace(arr[a - 4 + 3], "").EndsWith("{/if}", StringComparison.CurrentCultureIgnoreCase) == true) {
										var idx = arr[a - 4 + 3].IndexOf("{/if}");
										arr[a - 4 + 3] = string.Concat(arr[a - 4 + 3].Substring(0, idx), arr[a - 4 + 3].Substring(idx + 5));
										//如果 @else="有条件内容",则变换成 elseif 条件内容
										if (_reg_blank.Replace(arr[a + 2], "").Length > 0) a1 = "elseif";
										end3 = "{/if}";
									} else {
										arr[a] = string.Concat("指令 @", arr[a + 1], "='", arr[a + 2], "' 没紧接着 if/else 指令之后,无效. <", arr[a]);
										arr[a + 1] = arr[a + 2] = string.Empty;
									}
								}
								if (arr[a + 1].Length > 0) {
									if (_reg_blank.Replace(arr[a + 2], "").Length > 0 || a1.ToLower() == "else") {
										arr[b + 3] = string.Concat(arr[b + 3].Substring(0, fb + end.Length), end3, arr[b + 3].Substring(fb + end.Length));
										arr[a] = string.Concat("{", a1, " ", arr[a + 2], "}<", arr[a]);
										arr[a + 1] = arr[a + 2] = string.Empty;
									} else {
										arr[a] = string.Concat('<', arr[a]);
										arr[a + 1] = arr[a + 2] = string.Empty;
									}
								}
								break;
							}
							bpos = fb + end.Length;
						}
					}
					if (fc > 0) {
						arr[a] = string.Concat("不严谨的html格式,请检查 ", arr[a], " 的结束标签, @", arr[a + 1], "='", arr[a + 2], "' 指令无效. <", arr[a]);
						arr[a + 1] = arr[a + 2] = string.Empty;
					}
				}
				if (arr.Length > 0) tplcode = string.Join(string.Empty, arr);
			}
			return tplcode;
		}

19 Source : GlobalFunctions.cs
with MIT License
from 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 Source : SendPacket.cs
with MIT License
from 499116344

[Obsolete("请使用BinaryWriter.Write(Richtext)方法。")]
        public static byte[] ConstructMessage(string message)
        {
            var bw = new BinaryWriter(new MemoryStream());
            var r = new Regex(@"([^\[]+)*(\[face\d+\.gif\])([^\[]+)*");
            if (r.IsMatch(message))
            {
                var faces = r.Matches(message);
                for (var i = 0; i < faces.Count; i++)
                {
                    var face = faces[i];
                    for (var j = 1; j < face.Groups.Count; j++)
                    {
                        var group = face.Groups[j].Value;
                        if (group.Contains("[face") && group.Contains(".gif]"))
                        {
                            var faceIndex =
                                Convert.ToByte(group.Substring(5, group.Length - group.LastIndexOf(".") - 4));
                            if (faceIndex > 199)
                            {
                                faceIndex = 0;
                            }

                            //表情
                            bw.Write(new byte[] { 0x02, 0x00, 0x14, 0x01, 0x00, 0x01 });
                            bw.Write(faceIndex);
                            bw.Write(new byte[] { 0xFF, 0x00, 0x02, 0x14 });
                            bw.Write((byte) (faceIndex + 65));
                            bw.Write(new byte[] { 0x0B, 0x00, 0x08, 0x00, 0x01, 0x00, 0x04, 0x52, 0xCC, 0x85, 0x50 });
                        }
                        else if (!string.IsNullOrEmpty(group))
                        {
                            var groupMsg = Encoding.UTF8.GetBytes(group);
                            //普通消息
                            ConstructMessage(bw, groupMsg);
                        }
                    }
                }
            }

            return bw.BaseStream.ToBytesArray();
        }

19 Source : QQUser.cs
with MIT License
from 499116344

public GroupMembers Search_Group_Members(long externalId)
        {
            try
            {
                using (var httpWebClient = new HttpWebClient())
                {
                    var address = "https://qun.qq.com/cgi-bin/qun_mgr/search_group_members";
                    var s = $"gc={externalId}&st=0&end=10000&sort=0&bkn={Bkn}";
                    httpWebClient.Headers["Accept"] = "application/json, text/javascript, */*; q=0.01";
                    httpWebClient.Headers["Referer"] = "http://qun.qq.com/member.html";
                    httpWebClient.Headers["X-Requested-With"] = "XMLHttpRequest";
                    httpWebClient.Headers.Add("Cache-Control: no-cache");
                    httpWebClient.Headers["User-Agent"] = _ua;
                    httpWebClient.Cookies = QunCookies;
                    var text = Encoding.UTF8.GetString(httpWebClient.UploadData(address, "POST",
                        Encoding.UTF8.GetBytes(s)));

                    var r = new Regex("\"[0-9]+\":\"[^\"]+\"");
                    if (r.IsMatch(text))
                    {
                        foreach (var match in r.Matches(text))
                        {
                            var str = ((Capture) match).Value.Split(':');
                            var r2 = new Regex("\"[0-9]+\"");
                            var level = r2.Matches(str[0])[0].Value;
                            var r3 = new Regex("\"[^\"]+\"");
                            var name = r3.Matches(str[1])[0].Value;
                            var dataItem = "{\"level\":" + level + ",\"name\":" + name + "}";

                            text = text.Replace(((Capture) match).Value, dataItem);
                        }

                        text = text.Replace("\"levelname\":{", "\"levelname\":[")
                            .Replace("},\"max_count\"", "],\"max_count\"");
                    }

                    MessageLog($"获取群{externalId}成员列表成功:{(text.Length > 200 ? text.Substring(0, 200) : text)}");
                    return JsonConvert.DeserializeObject<GroupMembers>(text);
                }
            }
            catch (Exception ex)
            {
                MessageLog($"获取群{externalId}成员列表失败:{ex.Message}");
            }

            return null;
        }

19 Source : QQUser.cs
with MIT License
from 499116344

public FriendList Get_Friend_List()
        {
            try
            {
                using (var httpWebClient = new HttpWebClient())
                {
                    var address = "https://qun.qq.com/cgi-bin/qun_mgr/get_friend_list";
                    var s = $"bkn={Bkn}";
                    httpWebClient.Headers["Accept"] = "application/json, text/javascript, */*; q=0.01";
                    httpWebClient.Headers["Referer"] = "http://qun.qq.com/member.html";
                    httpWebClient.Headers["X-Requested-With"] = "XMLHttpRequest";
                    httpWebClient.Headers["User-Agent"] = _ua;
                    httpWebClient.Headers.Add("Cache-Control: no-cache");
                    httpWebClient.Cookies = QunCookies;
                    var text = Encoding.UTF8.GetString(httpWebClient.UploadData(address, "POST",
                        Encoding.UTF8.GetBytes(s)));
                    var r = new Regex("\"[0-9]+\":");
                    if (r.IsMatch(text))
                    {
                        foreach (var match in r.Matches(text))
                        {
                            var str = ((Capture) match).Value;
                            text = text.Replace(str, "");
                        }

                        text = text.Replace("\"result\":{{", "\"result\":[{").Replace("\"}}}", "\"}]}");
                    }

                    MessageLog("获取好友列表成功:" + text);
                    return JsonConvert.DeserializeObject<FriendList>(text);
                }
            }
            catch (Exception ex)
            {
                MessageLog("获取好友列表失败:" + ex.Message);
            }

            return null;
        }

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

public static bool IsEmail(string value)
        {
            if (value.IsNullOrEmpty())
            {
                return false;
            }

            var regex = new Regex(EmailRegex);
            return regex.IsMatch(value);
        }

19 Source : StringExtension.cs
with GNU Lesser General Public License v3.0
from 8720826

public static bool IsChinese(this string text)
        {
            Regex rx = new Regex("^[\u4e00-\u9fbb]{0,}$");
            return rx.IsMatch(text);
        }

19 Source : StringExtension.cs
with GNU Lesser General Public License v3.0
from 8720826

public static bool IsEmail(this string value)
        {
            var reg = new Regex(@"\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*");
            return string.IsNullOrEmpty(value) == false && reg.IsMatch(value);
        }

19 Source : helpers.cs
with MIT License
from 91Act

public static bool Like(this string str, string pattern)
        {
            return new Regex(
                "^" + Regex.Escape(pattern).Replace(@"\*", ".*").Replace(@"\?", ".") + "$",
                RegexOptions.IgnoreCase | RegexOptions.Singleline
            ).IsMatch(str);
        }

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

private static List<string> GetGltfMeshPrimitiveAttributes(string jsonString, Regex regex)
        {
            var jsonObjects = new List<string>();

            if (!regex.IsMatch(jsonString))
            {
                return jsonObjects;
            }

            MatchCollection matches = regex.Matches(jsonString);

            for (var i = 0; i < matches.Count; i++)
            {
                jsonObjects.Add(matches[i].Groups["Data"].Captures[0].Value);
            }

            return jsonObjects;
        }

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

private static Dictionary<string, string> GetGltfExtensions(string jsonString, Regex regex)
        {
            var jsonObjects = new Dictionary<string, string>();

            if (!regex.IsMatch(jsonString))
            {
                return jsonObjects;
            }

            var matches = regex.Matches(jsonString);
            var nodeName = string.Empty;

            for (var i = 0; i < matches.Count; i++)
            {
                for (int j = 0; j < matches[i].Groups.Count; j++)
                {
                    for (int k = 0; k < matches[i].Groups[i].Captures.Count; k++)
                    {
                        nodeName = GetGltfNodeName(matches[i].Groups[i].Captures[i].Value);
                    }
                }

                if (!jsonObjects.ContainsKey(nodeName))
                {
                    jsonObjects.Add(nodeName, GetJsonObject(jsonString, matches[i].Index + matches[i].Length));
                }
            }

            return jsonObjects;
        }

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

public bool RelativeDirectoryPathIsRelevant(string relativeDirName)
	{
		// Since our ignore patterns look at file names, they may contain trailing path separators
		// In order for paths to match those rules, we add a path separator here
		return !_ignoreExpression.IsMatch(EnsureTrailingDirectorySeparator(relativeDirName));
	}

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

private static int FindInScope(string search, int start, List<string> lines)
    {
        var regex = new System.Text.RegularExpressions.Regex(search);

        int depth = 0;

        for (int i = start; i < lines.Count; i++)
        {
            if (depth == 0 && regex.IsMatch(lines[i]))
            {
                return i;
            }

            // count the number of open and close braces. If we leave the current scope, break
            if (lines[i].Contains("{"))
            {
                depth++;
            }
            if (lines[i].Contains("}"))
            {
                depth--;
            }
            if (depth < 0)
            {
                break;
            }
        }
        return -1;
    }

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

public bool RelativeFilePathIsRelevant(string relativeFilename)
	{
		return !_ignoreExpression.IsMatch(relativeFilename);
	}

19 Source : UsingDonutChartExampleView.xaml.cs
with MIT License
from ABTSoftware

private void NewValueTBox_OnPreviewTextInput(object sender, TextCompositionEventArgs e)
        {
            Regex regex = new Regex("[^0-9]+");
            e.Handled = regex.IsMatch(e.Text);
        }

19 Source : UsingPieChartExampleView.xaml.cs
with MIT License
from ABTSoftware

private void UIElement_OnPreviewTextInput(object sender, TextCompositionEventArgs e)
        {
            Regex regex = new Regex("[^0-9]+");
            e.Handled = regex.IsMatch(e.Text);
        }

19 Source : DirectoryHelper.cs
with MIT License
from ABTSoftware

public static bool IsValidPath(string path, out string error)
        {
            error = null;
            switch (path)
            {
                case null: 
                    error = "Path can't be null";
                    return false;
                case "":
                    error = "";
                    return false;
            }

            if (path.Length < 3)
            {
                error = "Please set drive at least";
                return false;
            }

            string drive = path.Substring(0, 3);   // e.g. K:\

            var driveCheck = new Regex(@"^[a-zA-Z]:\\$");
            if (!driveCheck.IsMatch(drive))
            {
                error = @"Drive should be set in the following format: ""_:\"", where ""_"" is drive letter";
                return false;
            }

            if (!Directory.Exists(drive))
            {
                error = @"Drive " + drive + " not found or inaccessible";
                return false;
            }

            var strTheseAreInvalidFileNameChars = new string(Path.GetInvalidPathChars());
            strTheseAreInvalidFileNameChars += @":/?*" + "\"";

            var containsABadCharacter = new Regex("[" + Regex.Escape(strTheseAreInvalidFileNameChars) + "]");
            if (containsABadCharacter.IsMatch(path.Substring(3, path.Length - 3)))
            {
                error = "The given path's format is not supported";
                return false;
            }

            return true;
        }

19 Source : AppModuleUpgradeTask.cs
with MIT License
from Accelerider

private static string GetModuleInfoRef(string installPath)
        {
            var dllFilePath = Directory
                .GetFiles(installPath)
                .FirstOrDefault(item => ModuleFileRegex.IsMatch(Path.GetFileName(item)));

            return $"file:///{dllFilePath}";
        }

19 Source : CorrectionCandidate.cs
with GNU Lesser General Public License v3.0
from acnicholas

public bool MoveNext()
        {
            while (originalWords != null && currentIndex < (originalWords.Length - 1))
            {
                currentIndex++;

                // Continue if a number is found...
                if (rgx.IsMatch(Currentreplacedtring)) {
                    continue;
                }

                if (autoReplacementList.ContainsKey(Currentreplacedtring)) {
                    string replacement;
                    if (autoReplacementList.TryGetValue(Currentreplacedtring, out replacement)) {
                        // FIXME this reaplces the first, not the current.
                        ReplaceCurrent(replacement);
                        continue;
                    }
                }

                if (!hunspell.Spell(originalWords[currentIndex].Trim())) {
                    return false;
                }
            }

            // Reset here so any futures checks in this actually check the whole string.
            Reset();
            return true;
        }

19 Source : TemplateSchema.cs
with MIT License
from actions

private void Validate()
        {
            var oneOfPairs = new List<KeyValuePair<String, OneOfDefinition>>();

            foreach (var pair in Definitions)
            {
                var name = pair.Key;

                if (!s_definitionNameRegex.IsMatch(name ?? String.Empty))
                {
                    throw new ArgumentException($"Invalid definition name '{name}'");
                }

                var definition = pair.Value;

                // Delay validation for 'one-of' definitions
                if (definition is OneOfDefinition oneOf)
                {
                    oneOfPairs.Add(new KeyValuePair<String, OneOfDefinition>(name, oneOf));
                }
                // Otherwise validate now
                else
                {
                    definition.Validate(this, name);
                }
            }

            // Validate 'one-of' definitions
            foreach (var pair in oneOfPairs)
            {
                var name = pair.Key;
                var oneOf = pair.Value;
                oneOf.Validate(this, name);
            }
        }

19 Source : StepsContext.cs
with MIT License
from actions

public void SetOutput(
            string scopeName,
            string stepName,
            string outputName,
            string value,
            out string reference)
        {
            var step = GetStep(scopeName, stepName);
            var outputs = step["outputs"].replacedertDictionary("outputs");
            outputs[outputName] = new StringContextData(value);
            if (_propertyRegex.IsMatch(outputName))
            {
                reference = $"steps.{stepName}.outputs.{outputName}";
            }
            else
            {
                reference = $"steps['{stepName}']['outputs']['{outputName}']";
            }
        }

19 Source : RunnerWebProxyL0.cs
with MIT License
from actions

[Fact]
        [Trait("Level", "L0")]
        [Trait("Category", "Common")]
        public void IsNotUseRawHttpClient()
        {
            List<string> sourceFiles = Directory.GetFiles(
                    TestUtil.GetProjectPath("Runner.Common"),
                    "*.cs",
                    SearchOption.AllDirectories).ToList();
            sourceFiles.AddRange(Directory.GetFiles(
                     TestUtil.GetProjectPath("Runner.Listener"),
                     "*.cs",
                     SearchOption.AllDirectories));
            sourceFiles.AddRange(Directory.GetFiles(
                    TestUtil.GetProjectPath("Runner.Worker"),
                    "*.cs",
                    SearchOption.AllDirectories));

            List<string> badCode = new List<string>();
            foreach (string sourceFile in sourceFiles)
            {
                // Skip skipped files.
                if (SkippedFiles.Any(s => sourceFile.Contains(s)))
                {
                    continue;
                }

                // Skip files in the obj directory.
                if (sourceFile.Contains(StringUtil.Format("{0}obj{0}", Path.DirectorySeparatorChar)))
                {
                    continue;
                }

                int lineCount = 0;
                foreach (string line in File.ReadAllLines(sourceFile))
                {
                    lineCount++;
                    if (NewHttpClientRegex.IsMatch(line))
                    {
                        badCode.Add($"{sourceFile} (line {lineCount})");
                    }
                }
            }

            replacedert.True(badCode.Count == 0, $"The following code is using Raw HttpClient() which will not follow the proxy setting agent have. Please use New HttpClient(HostContext.CreateHttpClientHandler()) instead.\n {string.Join("\n", badCode)}");
        }

19 Source : RunnerWebProxyL0.cs
with MIT License
from actions

[Fact]
        [Trait("Level", "L0")]
        [Trait("Category", "Common")]
        public void IsNotUseRawHttpClientHandler()
        {
            List<string> sourceFiles = Directory.GetFiles(
                    TestUtil.GetProjectPath("Runner.Common"),
                    "*.cs",
                    SearchOption.AllDirectories).ToList();
            sourceFiles.AddRange(Directory.GetFiles(
                     TestUtil.GetProjectPath("Runner.Listener"),
                     "*.cs",
                     SearchOption.AllDirectories));
            sourceFiles.AddRange(Directory.GetFiles(
                    TestUtil.GetProjectPath("Runner.Worker"),
                    "*.cs",
                    SearchOption.AllDirectories));

            List<string> badCode = new List<string>();
            foreach (string sourceFile in sourceFiles)
            {
                // Skip skipped files.
                if (SkippedFiles.Any(s => sourceFile.Contains(s)))
                {
                    continue;
                }

                // Skip files in the obj directory.
                if (sourceFile.Contains(StringUtil.Format("{0}obj{0}", Path.DirectorySeparatorChar)))
                {
                    continue;
                }

                int lineCount = 0;
                foreach (string line in File.ReadAllLines(sourceFile))
                {
                    lineCount++;
                    if (NewHttpClientHandlerRegex.IsMatch(line))
                    {
                        badCode.Add($"{sourceFile} (line {lineCount})");
                    }
                }
            }

            replacedert.True(badCode.Count == 0, $"The following code is using Raw HttpClientHandler() which will not follow the proxy setting agent have. Please use HostContext.CreateHttpClientHandler() instead.\n {string.Join("\n", badCode)}");
        }

19 Source : TokenTypes.ReservedWord.cs
with MIT License
from adamant

public static bool IsReservedTypeName(string value)
        {
            return ReservedTypeNamePattern.IsMatch(value);
        }

19 Source : ConformanceTests.cs
with MIT License
from adamant

private static bool ExpectCompileErrors(string code)
        {
            return ExpectCompileErrorsPattern.IsMatch(code);
        }

19 Source : SqlServerXmlRepository.cs
with MIT License
from adamrushad

private static bool ValidateSqlIdentifier(string identifierName)
        {
            return _regex.IsMatch(identifierName);
        }

19 Source : AnnotationDataAdapter.cs
with MIT License
from Adoxio

public IAnnotationResult CreateAnnotation(IAnnotation note, IAnnotationSettings settings = null)
		{
			var serviceContext = _dependencies.GetServiceContext();
			var serviceContextForWrite = _dependencies.GetServiceContextForWrite();

			if (settings == null)
			{
				settings = new AnnotationSettings(serviceContext);
			}
			
			var storageAccount = GetStorageAccount(serviceContext);
			if (settings.StorageLocation == StorageLocation.AzureBlobStorage && storageAccount == null)
			{
				settings.StorageLocation = StorageLocation.CrmDoreplacedent;
			}

			AnnotationCreateResult result = null;

			if (settings.RespectPermissions)
			{
				var enreplacedyPermissionProvider = new CrmEnreplacedyPermissionProvider();
				result = new AnnotationCreateResult(enreplacedyPermissionProvider, serviceContext, note.Regarding);
			}

			// ReSharper disable once PossibleNullReferenceException
			if (!settings.RespectPermissions ||
				(result.PermissionsExist && result.PermissionGranted))
			{
				var enreplacedy = new Enreplacedy("annotation");

				if (note.Owner != null)
				{
					enreplacedy.SetAttributeValue("ownerid", note.Owner);
				}

				enreplacedy.SetAttributeValue("subject", note.Subject);
				enreplacedy.SetAttributeValue("notetext", note.NoteText);
				enreplacedy.SetAttributeValue("objectid", note.Regarding);
				enreplacedy.SetAttributeValue("objecttypecode", note.Regarding.LogicalName);

				if (note.FileAttachment != null)
				{
					var acceptMimeTypes = AnnotationDataAdapter.GetAcceptRegex(settings.AcceptMimeTypes);
					var acceptExtensionTypes = AnnotationDataAdapter.GetAcceptRegex(settings.AcceptExtensionTypes);
					if (!(acceptExtensionTypes.IsMatch(Path.GetExtension(note.FileAttachment.FileName).ToLower()) ||
							acceptMimeTypes.IsMatch(note.FileAttachment.MimeType)))
					{
						throw new AnnotationException(settings.RestrictMimeTypesErrorMessage);
					}

					if (settings.MaxFileSize.HasValue && note.FileAttachment.FileSize > settings.MaxFileSize)
					{
						throw new AnnotationException(settings.MaxFileSizeErrorMessage);
					}

					note.FileAttachment.Annotation = enreplacedy;

					switch (settings.StorageLocation)
					{
					case StorageLocation.CrmDoreplacedent:
						var crmFile = note.FileAttachment as CrmAnnotationFile;
						if (crmFile == null)
						{
							break;
						}

						if (!string.IsNullOrEmpty(settings.RestrictedFileExtensions))
						{
							var blocked = new Regex(@"\.({0})$".FormatWith(settings.RestrictedFileExtensions.Replace(";", "|")));
							if (blocked.IsMatch(crmFile.FileName))
							{
								throw new AnnotationException(settings.RestrictedFileExtensionsErrorMessage);
							}
						}

						enreplacedy.SetAttributeValue("filename", crmFile.FileName);
						enreplacedy.SetAttributeValue("mimetype", crmFile.MimeType);
						enreplacedy.SetAttributeValue("doreplacedentbody", Convert.ToBase64String(crmFile.Doreplacedent));
						break;
					case StorageLocation.AzureBlobStorage:
						enreplacedy.SetAttributeValue("filename", note.FileAttachment.FileName + ".azure.txt");
						enreplacedy.SetAttributeValue("mimetype", "text/plain");
						var fileMetadata = new
						{
							Name = note.FileAttachment.FileName,
							Type = note.FileAttachment.MimeType,
							Size = (ulong)note.FileAttachment.FileSize,
							Url = string.Empty
						};
						enreplacedy.SetAttributeValue("doreplacedentbody",
							Convert.ToBase64String(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(fileMetadata, Formatting.Indented))));
						break;
					}
				}

				// Create annotaion but skip cache invalidation.
				var id = (serviceContext as IOrganizationService).ExecuteCreate(enreplacedy, RequestFlag.ByPreplacedCacheInvalidation);

				if (result != null) result.Annotation = note;

				note.AnnotationId = enreplacedy.Id = id;
				note.Enreplacedy = enreplacedy;

				if (note.FileAttachment is AzureAnnotationFile && settings.StorageLocation == StorageLocation.AzureBlobStorage)
				{
					var container = GetBlobContainer(storageAccount, _containerName);

					var azureFile = (AzureAnnotationFile)note.FileAttachment;

					azureFile.BlockBlob = UploadBlob(azureFile, container, note.AnnotationId);

					var fileMetadata = new
					{
						Name = azureFile.FileName,
						Type = azureFile.MimeType,
						Size = (ulong)azureFile.FileSize,
						Url = azureFile.BlockBlob.Uri.AbsoluteUri
					};
					enreplacedy.SetAttributeValue("doreplacedentbody",
						Convert.ToBase64String(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(fileMetadata, Formatting.Indented))));
					serviceContextForWrite.UpdateObject(enreplacedy);
					serviceContextForWrite.SaveChanges();

					// NB: This is basically a hack to support replication. Keys are gathered up and stored during replication, and the
					// actual blob replication is handled here.
					var key = note.AnnotationId.ToString("N");
					if (HttpContext.Current.Application.AllKeys.Contains(NoteReplication.BlobReplicationKey))
					{
						var replication =
							HttpContext.Current.Application[NoteReplication.BlobReplicationKey] as Dictionary<string, Tuple<Guid, Guid>[]>;
						if (replication != null && replication.ContainsKey(key))
						{
							CopyBlob(note, replication[key]);
							replication.Remove(key);
						}
					}
				} 
			}

			if (FeatureCheckHelper.IsFeatureEnabled(FeatureNames.TelemetryFeatureUsage))
			{
				PortalFeatureTrace.TraceInstance.LogFeatureUsage(FeatureTraceCategory.Note, HttpContext.Current, "create_note", 1, note.Enreplacedy.ToEnreplacedyReference(), "create");
			}

			return result;
		}

19 Source : AnnotationDataAdapter.cs
with MIT License
from Adoxio

private IAnnotationFile GetAnnotationFile(Enreplacedy note, Guid id)
		{
			var isDoreplacedent = note.GetAttributeValue<bool>("isdoreplacedent");
			if (!isDoreplacedent) return null;

			var fileName = note.GetAttributeValue<string>("filename");

			var storageAccount = GetStorageAccount(_dependencies.GetServiceContext());
			var regex = new Regex(@"\.azure\.txt$");
			var azure = regex.IsMatch(fileName);

			var file = azure ? new AzureAnnotationFile() as IAnnotationFile : new CrmAnnotationFile();

			file.SetAnnotation(() => GetAnnotationWithDoreplacedent(id));

			if (azure)
			{
				var blobFileName = regex.Replace(fileName, string.Empty);
				var blobFile = file as AzureAnnotationFile;
				if (storageAccount != null)
				{
					blobFile.BlockBlob = GetBlockBlob(storageAccount, id, blobFileName);
					if (blobFile.BlockBlob.Exists())
					{
						blobFile.FileName = blobFileName;
						blobFile.FileSize = new FileSize(blobFile.BlockBlob == null ? 0 : Convert.ToUInt64(blobFile.BlockBlob.Properties.Length));
						blobFile.MimeType = blobFile.BlockBlob.Properties.ContentType;
					}
				}
			}
			else
			{
				var crmFile = file as CrmAnnotationFile;
				crmFile.FileName = fileName;
				var size = note.GetAttributeValue<int>("filesize");
				crmFile.FileSize = new FileSize(size > 0 ? Convert.ToUInt64(size) : 0);
				crmFile.MimeType = note.GetAttributeValue<string>("mimetype");
				crmFile.SetDoreplacedent(() => GetFileDoreplacedent(file));
			}


			return file;
		}

19 Source : Mask.cs
with MIT License
from Adoxio

public virtual bool IsMatch(string input)
		{
			return InnerRegex.IsMatch(input);
		}

19 Source : NumberFormatFilters.cs
with MIT License
from Adoxio

public static string MaxDecimals(object number, int decimals, string culture = "")
		{
			var result = Decimals(number, decimals, culture);
			if (new Regex(string.Format("\\{0}", CultureInfo.CurrentUICulture.NumberFormat.NumberDecimalSeparator)).IsMatch(result))
			{
				var zeroRegex = new Regex("0+$");
				var decimalRegex = new Regex(string.Format("\\{0}$", CultureInfo.CurrentUICulture.NumberFormat.NumberDecimalSeparator));
				result = zeroRegex.Replace(result, string.Empty);
				result = decimalRegex.Replace(result, string.Empty);
			}
			return result;
		}

19 Source : LiquidServerControl.cs
with MIT License
from Adoxio

private void AddTemplate(string html)
		{
			var regex = new Regex(@"\<!--\[% (\w+) id:([A-F0-9]{8}(?:-[A-F0-9]{4}){3}-[A-F0-9]{12})? %\]--\>",
				RegexOptions.IgnoreCase);

			Control container = this;

			if (regex.IsMatch(html))
			{
				container = ServerForm(container);
			}

			while (regex.IsMatch(html))
			{
				var match = regex.Match(html);

				var control = match.Groups[1].Value;
				var id = match.Groups[2].Value;
				Guid guid;
				if (Guid.TryParse(id, out guid))
				{
					var splits = html.Split(new[] { match.Value }, StringSplitOptions.RemoveEmptyEntries);
					var preSplit = new LiteralControl(splits[0]);
					container.Controls.Add(preSplit);

					switch (control)
					{
					case "enreplacedyform":
						var enreplacedyForm = InitEnreplacedyForm(guid);
						container.Controls.Add(enreplacedyForm);
						break;
					case "webform":
						var webForm = InitWebForm(guid);
						container.Controls.Add(webForm);
						break;
					}

					html = string.Join(match.Value, splits.Skip(1));
				}
			}

			var close = new LiteralControl(html);
			container.Controls.Add(close);
		}

19 Source : DialoguePatches.cs
with GNU General Public License v3.0
from aedenthorn

public static void FixString(NPC speaker, ref string input)
        {

            //Monitor.Log($"checking string: {input}");

            Regex pattern1 = new Regex(prefix + @"(?<key>[^\^]+)", RegexOptions.Compiled);

            while (pattern1.IsMatch(input))
            {
                var match = pattern1.Match(input);
                Dictionary<string, string> dialogueDic = null;
                try
                {
                    dialogueDic = Helper.Content.Load<Dictionary<string, string>>($"Characters/Dialogue/{speaker.Name}", ContentSource.GameContent);
                }
                catch
                {
                }

                string key = match.Groups["key"].Value;

                if (dialogueDic != null && dialogueDic.ContainsKey(key))
                {
                    Regex pattern2 = new Regex(prefix + key + @"\^.*\^" + suffix + key, RegexOptions.Compiled);
                    Monitor.Log($"{speaker.Name} has dialogue for {key}", LogLevel.Debug);
                    input = pattern2.Replace(input, dialogueDic[key]);
                }
                else
                {
                    //Monitor.Log($"edited input: {input}");
                    input = input.Replace($"^{suffix}{key}", "").Replace($"{prefix}{key}^","");
                    Monitor.Log($"reverted input: {input}");
                }
            }
        }

19 Source : DialoguePatches.cs
with GNU General Public License v3.0
from aedenthorn

public static void FixString(NPC speaker, ref string input)
        {

           Monitor.Log($"checking string: {input}");

            Regex pattern1 = new Regex(prefix + @"(?<key>[^\^]+)", RegexOptions.Compiled);

            while (pattern1.IsMatch(input))
            {
                string oldput = input;
                var match = pattern1.Match(input);
                string key = match.Groups["key"].Value;
                Dictionary<string, string> dialogueDic = null;
                try
                {
                    dialogueDic = Helper.Content.Load<Dictionary<string, string>>($"Characters/Dialogue/{speaker.Name}", ContentSource.GameContent);
                }
                catch(Exception ex)
                {
                    Monitor.Log($"Error loading character dictionary for {speaker.Name}:\r\n{ex}");
                    input = input.Replace($"^{suffix}{key}", "").Replace($"{prefix}{key}^", "");
                    Monitor.Log($"reverted input: {input}");
                }


                if (dialogueDic != null && dialogueDic.ContainsKey(key))
                {
                    Regex pattern2 = new Regex(prefix + key + @"\^.*\^" + suffix + key, RegexOptions.Compiled);
                    Monitor.Log($"{speaker.Name} has dialogue for {key}", LogLevel.Debug);
                    input = pattern2.Replace(input, dialogueDic[key]);
                }
                else
                {
                    //Monitor.Log($"edited input: {input}");
                    input = input.Replace($"^{suffix}{key}", "").Replace($"{prefix}{key}^", "");
                    Monitor.Log($"reverted input: {input}");
                }
                Monitor.Log($"edited string: {input}");
                if (input == oldput)
                {
                    Monitor.Log($"Error editing input, aborting.", LogLevel.Error);
                    return;
                }
            }
        }

19 Source : ModEntry.cs
with GNU General Public License v3.0
from aedenthorn

public bool CanEdit<T>(IreplacedetInfo replacedet)
        {
            string replacedetName = replacedet.replacedetName;
            Regex rgx = new Regex(@"^Maps/Mines/[0-9]{1,2}$");

            if (rgx.IsMatch(replacedetName))
            {
                return true;
            }

            return false;
        }

19 Source : AnarchyExtensions.cs
with GNU General Public License v3.0
from aelariane

public static string ToHTMLFormat(this string str)
        {
            if (hexCode.IsMatch(str))
            {
                str = str.Contains("[-]")
                    ? hexCode.Replace(str, "<color=#$1>").Replace("[-]", "</color>")
                    : hexCode.Replace(str, "<color=#$1>");
                var c = (short)(str.CountWords("<color=") - str.CountWords("</color>"));
                for (short i = 0; i < c; i++)
                {
                    str += "</color>";
                }
            }

            return str;
        }

19 Source : AG0027EnsureOnlyDataSeleniumIsUsedToFindElements.cs
with Apache License 2.0
from agoda-com

private static void replacedyzeNode(SyntaxNodereplacedysisContext context)
        {
            var invocationExpressionSyntax = (InvocationExpressionSyntax) context.Node;

            if (!(context.SemanticModel.GetSymbolInfo(invocationExpressionSyntax).Symbol is IMethodSymbol))
            {
                return;
            }

            if (!TestMethodHelpers.PermittedSeleniumAccessors.Any(accessor => accessor.IsMatch(context)))
            {
                return;
            }
            
            // check string literal
            var firstArgument = invocationExpressionSyntax.ArgumentList.Arguments.FirstOrDefault();
            if (firstArgument?.Expression is LiteralExpressionSyntax && !MatchDataSelenium.IsMatch(firstArgument.ToString()))
            {
                context.ReportDiagnostic(Diagnostic.Create(Descriptor, firstArgument.GetLocation()));
            }

            if (!(firstArgument?.Expression is IdentifierNameSyntax))
            {
                return;
            }
            
            // check compile-time constant
            var constantValue = context.SemanticModel.GetConstantValue(firstArgument.Expression);
            if (constantValue.HasValue && !MatchDataSelenium.IsMatch($@"""{constantValue.Value}"""))
            {
                context.ReportDiagnostic(Diagnostic.Create(Descriptor, firstArgument.GetLocation()));
            }
        }

19 Source : AG0037EnsureSeleniumTestHasOwnedByAttribute.cs
with Apache License 2.0
from agoda-com

private void replacedyzeMethodDeclaration(SyntaxNodereplacedysisContext context)
        {
            var methodSyntax = (MethodDeclarationSyntax) context.Node;
            var methodSymbol = context.SemanticModel.GetDeclaredSymbol(methodSyntax);

            // check the method is declared in the right namespace
            if (!MatchNamespaces.Any(r => r.IsMatch(methodSymbol.ContainingNamespace.ToString())))
            {
                return;
            }

            // ensure it's a test method
            if (!TestMethodHelpers.IsTestCase(methodSyntax, context))
            {
                return;
            }

            // check if the method has the attribute 
            if (methodSymbol.GetAttributes().Any(a => a.AttributeClreplaced.Name == OWNED_BY_ATTRIBUTE_CLreplaced_NAME))
            {
                return;
            }
            
            // check if the clreplaced has the attribute
            var clreplacedHasAttribute = methodSyntax.Ancestors()
                .OfType<ClreplacedDeclarationSyntax>()
                .SelectMany(clreplacedDeclarationSyntax => context.SemanticModel.GetDeclaredSymbol(clreplacedDeclarationSyntax).GetAttributes())
                .Any(a => a.AttributeClreplaced.Name == OWNED_BY_ATTRIBUTE_CLreplaced_NAME);
            
            if (clreplacedHasAttribute)
            {
                return;
            }
            
            context.ReportDiagnostic(Diagnostic.Create(Descriptor, context.Node.GetLocation()));
        }

19 Source : AsyncHelpers.cs
with Apache License 2.0
from agoda-com

public static bool IsAsyncIntent(IMethodSymbol method)
        {
            return method.IsAsync || MatchTaskReturnType.IsMatch(method.ReturnType.ToDisplayString());
        }

19 Source : InvocationRule.cs
with Apache License 2.0
from agoda-com

public bool Verify(string namespaceAndType, string name)
        {
            if (namespaceAndType != _namespaceAndType)
            {
                return true;
            }
            var isPermitted = _names.Any(regex => regex.IsMatch(name));
            return _isBlacklist ? !isPermitted : isPermitted;
        }

19 Source : InvocationRule.cs
with Apache License 2.0
from agoda-com

private bool IsMatch(string namespaceAndType, string name)
        {
            return namespaceAndType == _namespaceAndType && _names.Any(regex => regex.IsMatch(name));
        }

19 Source : UriValidator.cs
with Apache License 2.0
from Aguafrommars

public override bool IsValid(ValidationContext<T> context, string value)
        {
            if (!string.IsNullOrEmpty(value))
            {
                return _urlRegex.IsMatch(value);
            }
            return true;
        }

19 Source : UpdateChecker.cs
with GNU General Public License v3.0
from AHeroicLlama

public static async void CheckForUpdate(bool userTriggered)
		{
			HttpResponseMessage response;

			try
			{
				// Get the latest release info from GitHub API
				HttpClient httpClient = new HttpClient();
				httpClient.DefaultRequestHeaders.Add("User-Agent", "AHeroicLlama/Mappalachia");
				response = await httpClient.GetAsync("https://api.github.com/repos/AHeroicLlama/Mappalachia/releases/latest");

				if (!response.IsSuccessStatusCode)
				{
					if (userTriggered)
					{
						CheckForUpdatesManual("HTTP request error: " + response.StatusCode);
					}

					return;
				}
			}
			catch (Exception)
			{
				if (userTriggered)
				{
					CheckForUpdatesManual("Networking error attempting to check for updates.");
				}

				return;
			}

			try
			{
				// Extract the value of 'tag_name' from the json string
				string responseContent = await response.Content.ReadreplacedtringAsync();
				string tagName = "\"tag_name\":";
				int tagValueStart = responseContent.IndexOf(tagName) + tagName.Length;
				int tagValueLength = responseContent.Substring(tagValueStart).IndexOf(",");
				string latestVersion = responseContent.Substring(tagValueStart, tagValueLength).Replace("\"", string.Empty);

				// Verify the version string is in the format "x.y.y.y" where x is 1-999 and y is 0-999
				Regex verifyVersion = new Regex(@"^[1-9]{1,3}(\.[0-9]{1,3}){3}$");

				// We got a valid version string from GitHub
				if (verifyVersion.IsMatch(latestVersion))
				{
					if (currentVersion != latestVersion)
					{
						PromptForUpdate(latestVersion);
					}
					else if (userTriggered)
					{
						Notify.Info("Mappalachia is up to date.\n" +
							"(Version " + currentVersion + ")");
					}
				}
				else
				{
					throw new ArgumentException("Version number parsed from response was of an incorrect format.");
				}
			}
			catch (Exception)
			{
				if (userTriggered)
				{
					CheckForUpdatesManual("Unable to correctly identify latest release from API response.");
				}

				return;
			}
		}

19 Source : LicensePacker.cs
with MIT License
from AhmedMinegames

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

19 Source : Program.cs
with MIT License
from AhmedMinegames

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

19 Source : Main.cs
with MIT License
from AhmedMinegames

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

19 Source : Main.cs
with MIT License
from AhmedMinegames

private void LicensePacking(string FileToPack, string Output)
        {
            var Options = new Dictionary<string, string>();
            Options.Add("CompilerVersion", "v4.0");
            Options.Add("language", "c#");
            var codeProvider = new CSharpCodeProvider(Options);
            CompilerParameters parameters = new CompilerParameters();
            parameters.CompilerOptions = "/target:winexe";
            parameters.GenerateExecutable = true;
            parameters.Outputreplacedembly = Output;
            parameters.IncludeDebugInformation = false;
            string[] Librarys = { "System", "System.Windows.Forms", "System.Management", "System.Net", "System.Core", "System.Net.Http", "System.Runtime", "System.Runtime.InteropServices" };
            foreach (string Library in Librarys)
            {
                parameters.Referencedreplacedemblies.Add(Library + ".dll");
            }
            byte[] CodeToProtect = File.ReadAllBytes(FileToPack);
            string RandomIV = RandomPreplacedword(16);
            AesAlgorithms EncryptingBytes = new AesAlgorithms();
            string RandomKey = RandomPreplacedword(4);
            Random rnd = new Random();
            int RandomINT = rnd.Next(6, 13);
            string RandomHashingKey = RandomPreplacedword(RandomINT);
            StringBuilder ROT13Encoding = new StringBuilder();
            Regex regex = new Regex("[A-Za-z]");
            foreach (char KSXZ in XOREncryptionKeys(textBox3.Text, RandomKey))
            {
                if (regex.IsMatch(KSXZ.ToString()))
                {
                    int C = ((KSXZ & 223) - 52) % 26 + (KSXZ & 32) + 65;
                    ROT13Encoding.Append((char)C);
                }
            }
            StringBuilder sb = new StringBuilder(); foreach (char c in ROT13Encoding.ToString().ToCharArray()) { sb.Append(Convert.ToString(c, 2).PadLeft(8, '0')); }
            var GetTextToHEX = Encoding.Unicode.GetBytes(sb.ToString());
            var BuildHEX = new StringBuilder();
            foreach (var FinalHEX in GetTextToHEX)
            {
                BuildHEX.Append(FinalHEX.ToString("X2"));
            }
            string HashedKey = UTF8Encoding.UTF8.GetString(MD5.Create().ComputeHash(UTF8Encoding.UTF8.GetBytes(BuildHEX.ToString())));
            HMACMD5 HMACMD = new HMACMD5();
            HMACMD.Key = UTF8Encoding.UTF8.GetBytes("LXSO12".Replace(UTF8Encoding.UTF8.GetString(Convert.FromBase64String("TFhTTzEy")), RandomHashingKey));
            string HashedKey2 = UTF8Encoding.UTF8.GetString(HMACMD.ComputeHash(UTF8Encoding.UTF8.GetBytes(HashedKey)));
            string Final = EncryptingBytes.AesTextEncryption(Convert.ToBase64String(CodeToProtect), HashedKey2.ToString(), RandomIV);
            string LicensePacker = Resource1.LicensePacker;
            string NewLicensePackerCode = LicensePacker.Replace("DecME", Final).Replace("THISISIV", RandomIV).Replace("LicensePacker", "namespace " + RandomName(14));
            string MyShinyNewPacker = NewLicensePackerCode.Replace("decryptkeyencryption", Convert.ToBase64String(Encoding.UTF8.GetBytes(RandomKey))).Replace("SOS13", textBox4.Text).Replace(UTF8Encoding.UTF8.GetString(Convert.FromBase64String("TFhTTzEy")), RandomHashingKey);
            codeProvider.CompilereplacedemblyFromSource(parameters, MyShinyNewPacker);
        }

19 Source : Utilities.cs
with MIT License
from Aiko-IT-Systems

internal static bool IsValidSlashCommandName(string name)
        {
            var regex = new Regex(@"^[\w-]{1,32}$", RegexOptions.ECMAScript);
            return regex.IsMatch(name);
        }

See More Examples