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

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

1590 Examples 7

19 View Source File : DbContext.cs
License : Apache License 2.0
Project Creator : 1448376744

private void Initialize(IDbCommand cmd, string sql, object parameter, int? commandTimeout = null, CommandType? commandType = null)
        {
            var dbParameters = new List<IDbDataParameter>();
            cmd.Transaction = _transaction;
            cmd.CommandText = sql;
            if (commandTimeout.HasValue)
            {
                cmd.CommandTimeout = commandTimeout.Value;
            }
            if (commandType.HasValue)
            {
                cmd.CommandType = commandType.Value;
            }
            if (parameter is IDbDataParameter)
            {
                dbParameters.Add(parameter as IDbDataParameter);
            }
            else if (parameter is IEnumerable<IDbDataParameter> parameters)
            {
                dbParameters.AddRange(parameters);
            }
            else if (parameter is Dictionary<string, object> keyValues)
            {
                foreach (var item in keyValues)
                {
                    var param = CreateParameter(cmd, item.Key, item.Value);
                    dbParameters.Add(param);
                }
            }
            else if (parameter != null)
            {
                var handler = GlobalSettings.EnreplacedyMapperProvider.GetDeserializer(parameter.GetType());
                var values = handler(parameter);
                foreach (var item in values)
                {
                    var param = CreateParameter(cmd, item.Key, item.Value);
                    dbParameters.Add(param);
                }
            }
            if (dbParameters.Count > 0)
            {
                foreach (IDataParameter item in dbParameters)
                {
                    if (item.Value == null)
                    {
                        item.Value = DBNull.Value;
                    }
                    var pattern = [email protected]"in\s+([\@,\:,\?]?{item.ParameterName})";
                    var options = RegexOptions.IgnoreCase | RegexOptions.Singleline | RegexOptions.Multiline;
                    if (cmd.CommandText.IndexOf("in", StringComparison.OrdinalIgnoreCase) != -1 && Regex.IsMatch(cmd.CommandText, pattern, options))
                    {
                        var name = Regex.Match(cmd.CommandText, pattern, options).Groups[1].Value;
                        var list = new List<object>();
                        if (item.Value is IEnumerable<object> || item.Value is Array)
                        {
                            list = (item.Value as IEnumerable).Cast<object>().Where(a => a != null && a != DBNull.Value).ToList();
                        }
                        else
                        {
                            list.Add(item.Value);
                        }
                        if (list.Count() > 0)
                        {
                            cmd.CommandText = Regex.Replace(cmd.CommandText, name, $"({string.Join(",", list.Select(s => $"{name}{list.IndexOf(s)}"))})");
                            foreach (var iitem in list)
                            {
                                var key = $"{item.ParameterName}{list.IndexOf(iitem)}";
                                var param = CreateParameter(cmd, key, iitem);
                                cmd.Parameters.Add(param);
                            }
                        }
                        else
                        {
                            cmd.CommandText = Regex.Replace(cmd.CommandText, name, $"(SELECT 1 WHERE 1 = 0)");
                        }
                    }
                    else
                    {
                        cmd.Parameters.Add(item);
                    }
                }
            }
            if (Logging != null)
            {
                var parameters = new Dictionary<string, object>();
                foreach (IDbDataParameter item in cmd.Parameters)
                {
                    parameters.Add(item.ParameterName, item.Value);
                }
                Logging.Invoke(cmd.CommandText, parameters, commandTimeout, commandType);
            }
        }

19 View Source File : ApplicationBuilderExtension.cs
License : MIT License
Project Creator : a34546

public async Task Invoke(HttpContext context)
        {
            var path = context.Request.Path;
            if (path.HasValue)
            {
                var pathValue = path.Value;
                if (pathValue.StartsWith("/")) pathValue = pathValue.Substring(1);
                if (Regex.IsMatch(pathValue, @"^[a-zA-Z0-9]{6}$"))
                {
                    var urlMappingRepository = (IUrlMappingRepository)context.RequestServices.GetService(typeof(IUrlMappingRepository));
                    var longUrl = await urlMappingRepository.GetUrlByCode(pathValue);
                    if (!string.IsNullOrEmpty(longUrl))
                    {
                        if (!Regex.IsMatch(longUrl, "(file|gopher|news|nntp|telnet|http|ftp|https|ftps|sftp)://", RegexOptions.IgnoreCase))
                        {
                            longUrl = "http://" + longUrl;
                        }
                        context.Response.Redirect(longUrl, true);
                        return;
                    }
                }
            }
            await _next.Invoke(context);
        }

19 View Source File : DellFanManagementGuiForm.cs
License : GNU General Public License v3.0
Project Creator : AaronKelley

private void ConsistencyModeTextBoxesChangedEventHandler(Object sender, EventArgs e)
        {
            // Enforce digits only in these text boxes.
            if (Regex.IsMatch(consistencyModeLowerTemperatureThresholdTextBox.Text, "[^0-9]"))
            {
                consistencyModeLowerTemperatureThresholdTextBox.Text = Regex.Replace(consistencyModeLowerTemperatureThresholdTextBox.Text, "[^0-9]", "");
            }

            if (Regex.IsMatch(consistencyModeUpperTemperatureThresholdTextBox.Text, "[^0-9]"))
            {
                consistencyModeUpperTemperatureThresholdTextBox.Text = Regex.Replace(consistencyModeUpperTemperatureThresholdTextBox.Text, "[^0-9]", "");
            }

            if (Regex.IsMatch(consistencyModeRpmThresholdTextBox.Text, "[^0-9]"))
            {
                consistencyModeRpmThresholdTextBox.Text = Regex.Replace(consistencyModeRpmThresholdTextBox.Text, "[^0-9]", "");
            }

            CheckConsistencyModeOptionsConsistency();
        }

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

static bool AppIDFieldValidator(string fieldText, ref string error)
		{
			if (string.IsNullOrEmpty(fieldText))
			{
				error = "The field is empty.";
				return false;
			}
			else if (!Regex.IsMatch(OVRPlatformToolSettings.AppID, "^[0-9]+$"))
			{
				error = "The field contains invalid characters.";
				return false;
			}
			return true;
		}

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

private void FilterByNumber(string number)
        {
            Manager.CurrentViewNumber(exportManager.Doc);
            try {
                var filter = new Predicate<object>(item =>
                    Regex.IsMatch(((ExportSheet)item).SheetNumber, @"^\D*" + number));
                Sheets.Filter = filter;
            }
            catch (Exception exception) {
                SCaddinsApp.WindowManager.ShowMessageBox(exception.Message);
            }
        }

19 View Source File : SimpleEditor.cs
License : GNU General Public License v3.0
Project Creator : adam8797

private void AutoIndent_InsertCheck(object sender, InsertCheckEventArgs e)
        {
            if (_styler != null)
            {
                if (e.Text.EndsWith("\r") || e.Text.EndsWith("\n"))
                {
                    int startPos = Lines[LineFromPosition(CurrentPosition)].Position;
                    int endPos = e.Position;
                    string curLineText = GetTextRange(startPos, (endPos - startPos));
                        //Text until the caret so that the whitespace is always equal in every line.

                    Match indent = Regex.Match(curLineText, "^[ \\t]*");
                    e.Text = (e.Text + indent.Value);
                    if (Regex.IsMatch(curLineText, _styler.IndentChar + "\\s*$"))
                    {
                        e.Text = (e.Text + "    ");
                    }
                }
            }
        }

19 View Source File : Name.cs
License : MIT License
Project Creator : adamant

public override string ToString()
        {
            if (TokenTypes.Keywords.Contains(Text)
               ||TokenTypes.ReservedWords.Contains(Text))
                return '\\' + Text;

            var text = Text.Escape();
            if (NeedsQuoted.IsMatch(text)) text += [email protected]"\""{text}""";
            return text;
        }

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

private async Task ValidateUserName(TUser user, List<string> errors)
		{
			if (string.IsNullOrWhiteSpace(user.UserName))
			{
				errors.Add(ToResult(IdenreplacedyErrors.InvalidUserName(user.UserName)));
			}
			else if (AllowOnlyAlphanumericUserNames && !Regex.IsMatch(user.UserName, @"^[[email protected]_\.]+$"))
			{
				errors.Add(ToResult(IdenreplacedyErrors.InvalidUserName(user.UserName)));
			}

			// block commas in usernames to prevent exceptions in the role provider

			else if (user.UserName.Contains(","))
			{
				errors.Add(ToResult(IdenreplacedyErrors.InvalidUserNameWithComma(user.UserName)));
			}
			else
			{
				var owner = await Manager.FindByNameAsync(user.UserName).WithCurrentCulture();
				if (owner != null && !EqualityComparer<TKey>.Default.Equals(owner.Id, user.Id))
				{
					errors.Add(ToResult(IdenreplacedyErrors.DuplicateUserName(user.UserName)));
				}
			}
		}

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

public virtual bool Validate(PluginMessage message)
		{
			IEnumerable<string> patterns;

			if (message.Target == null
				|| string.IsNullOrWhiteSpace(message.Target.LogicalName)
				|| !_enreplacediesToRestart.TryGetValue(message.Target.LogicalName, out patterns))
			{
				return false;
			}

			return patterns.Contains(".*")
				|| (!string.IsNullOrWhiteSpace(message.Target.Name)
				&& patterns.Any(pattern => Regex.IsMatch(message.Target.Name, pattern)));
		}

19 View Source File : AnnotationDataAdapter.cs
License : MIT License
Project Creator : 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 View Source File : AnnotationDataAdapter.cs
License : MIT License
Project Creator : Adoxio

public IAnnotationResult UpdateAnnotation(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;
			}

			AnnotationUpdateResult result = null;

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

			var isPostedByCurrentUser = false;
			var noteContact = AnnotationHelper.GetNoteContact(note.Enreplacedy.GetAttributeValue<string>("subject"));
			var currentUser = _dependencies.GetPortalUser();
			if (noteContact != null && currentUser != null && currentUser.LogicalName == "contact" &&
				currentUser.Id == noteContact.Id)
			{
				isPostedByCurrentUser = true;
			}

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

				enreplacedy.SetAttributeValue("notetext", note.NoteText);
				enreplacedy.SetAttributeValue("subject", note.Subject);
				enreplacedy.SetAttributeValue("isdoreplacedent", note.FileAttachment != null);
				
				if (note.FileAttachment != null)
				{
					var accept = GetAcceptRegex(settings.AcceptMimeTypes);
					if (!accept.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 || crmFile.Doreplacedent == null || crmFile.Doreplacedent.Length == 0)
						{
							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;
					}
				}

				serviceContextForWrite.Attach(enreplacedy);
				serviceContextForWrite.UpdateObject(enreplacedy);
				serviceContextForWrite.SaveChanges();

				if (note.FileAttachment is AzureAnnotationFile && settings.StorageLocation == StorageLocation.AzureBlobStorage)
				{
					var azureFile = note.FileAttachment as AzureAnnotationFile;

					if (azureFile.GetFileStream() != null)
					{
						var container = GetBlobContainer(storageAccount, _containerName);

						var oldName = note.Enreplacedy.GetAttributeValue<string>("filename");
						var oldBlob = container.GetBlockBlobReference("{0:N}/{1}".FormatWith(enreplacedy.Id.ToString(), oldName));
						oldBlob.DeleteIfExists();

						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();
					}
				}
			}

			if (FeatureCheckHelper.IsFeatureEnabled(FeatureNames.TelemetryFeatureUsage))
			{
				PortalFeatureTrace.TraceInstance.LogFeatureUsage(FeatureTraceCategory.Note, HttpContext.Current, "edit_note", 1, new EnreplacedyReference("annotation", note.AnnotationId), "edit");
			}

			return result;
		}

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

protected virtual DirectoryContent GetDirectoryContent(WebFileNode node)
		{
			if (node == null)
			{
				return null;
			}

			var fileNote = node.Annotations
				.Where(e => e.IsDoreplacedent.GetValueOrDefault())
				.OrderByDescending(e => e.CreatedOn)
				.FirstOrDefault();

			if (fileNote == null)
			{
				return null;
			}
			
			string url;

			try
			{
				url = ContentMapUrlProvider.GetUrl(ContentMap, node);
			}
			catch (Exception e)
			{
				ADXTrace.Instance.TraceError(TraceCategory.Application, string.Format("Error getting URL for enreplacedy [adx_webfile:{0}]: {1}", Node.Id, e.ToString()));

                return null;
			}

			if (url == null)
			{
				return null;
			}

			var enreplacedy = node.ToEnreplacedy();

			if (!ServiceContext.IsAttached(enreplacedy))
			{
				enreplacedy = ServiceContext.MergeClone(enreplacedy);
			}

			bool canWrite;

			try
			{
				if (!SecurityProvider.Tryreplacedert(ServiceContext, enreplacedy, CrmEnreplacedyRight.Read))
				{
					return null;
				}

				canWrite = SecurityProvider.Tryreplacedert(ServiceContext, enreplacedy, CrmEnreplacedyRight.Change);
			}
			catch (InvalidOperationException e)
			{
				ADXTrace.Instance.TraceError(TraceCategory.Application, string.Format("Error validating security for enreplacedy [adx_webfile:{0}]: {1}", Node.Id, e.ToString()));

                return null;
			}

			var azure = new Regex(@"\.azure\.txt$").IsMatch(fileNote.FileName);

			return new DirectoryContent
			{
				hash = new DirectoryContentHash(enreplacedy).ToString(),
				name = node.Name,
				mime = azure ? "application/x-azure-blob" : fileNote.MimeType,
				size = azure ? 0 : fileNote.FileSize.GetValueOrDefault(),
				url = url,
				date = FormatDateTime(node.ModifiedOn),
				read = true,
				write = canWrite,
				rm = canWrite
			};
		}

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

private bool TryGetFullPath(string templatePath, out string fullPath)
		{
			fullPath = null;

			if (templatePath == null || !Regex.IsMatch(templatePath, @"^[a-zA-Z0-9_][a-zA-Z0-9_\/]*$"))
			{
				return false;
			}

			try
			{
				fullPath = templatePath.Contains("/")
					? Path.Combine(Path.Combine(Root, Path.GetDirectoryName(templatePath)), "{0}.liquid".FormatWith(Path.GetFileName(templatePath)))
					: Path.Combine(Root, "{0}.liquid".FormatWith(templatePath));

				var escapedPath = Root.Replace(@"\", @"\\").Replace("(", @"\(").Replace(")", @"\)");

				return Regex.IsMatch(Path.GetFullPath(fullPath), "^{0}".FormatWith(escapedPath));
			}
			catch (System.ArgumentException)
			{
				return false;
			}
		}

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

public static EmbeddedResourcereplacedemblyAttribute Match(this IEnumerable<EmbeddedResourcereplacedemblyAttribute> attributes, string path)
		{
			var appRelativePath = VirtualPathUtility.ToAppRelative(path);
			var relativePath = VirtualPathUtility.IsAppRelative(appRelativePath) ? appRelativePath : "~" + appRelativePath;

			return attributes.FirstOrDefault(m => Regex.IsMatch(relativePath, m.VirtualPathMask, RegexOptions.IgnoreCase));
		}

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

protected void ValidateFileUpload(object source, ServerValidateEventArgs args)
		{
			args.IsValid = true;

			if (!NewForumThreadAttachment.HasFiles) return;

			if (AnnotationSettings.StorageLocation != StorageLocation.CrmDoreplacedent) return;

			if (string.IsNullOrEmpty(AnnotationSettings.RestrictedFileExtensions)) return;

			var blocked = new Regex(@"\.({0})$".FormatWith(AnnotationSettings.RestrictedFileExtensions.Replace(";", "|")));

			foreach (var uploadedFile in NewForumThreadAttachment.PostedFiles)
			{
				args.IsValid = !blocked.IsMatch(uploadedFile.FileName);

				if (!args.IsValid)
				{
					break;
				}
			}
		}

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

protected void ValidateFileUpload(object source, ServerValidateEventArgs args)
		{
			args.IsValid = true;

			if (!NewForumPostAttachment.HasFiles) return;

			if (AnnotationSettings.StorageLocation != StorageLocation.CrmDoreplacedent) return;

			if (string.IsNullOrEmpty(AnnotationSettings.RestrictedFileExtensions)) return;

			var blocked = new Regex(@"\.({0})$".FormatWith(AnnotationSettings.RestrictedFileExtensions.Replace(";", "|")));

			foreach (var uploadedFile in NewForumPostAttachment.PostedFiles)
			{
				args.IsValid = !blocked.IsMatch(uploadedFile.FileName);

				if (!args.IsValid)
				{
					break;
				}
			}
		}

19 View Source File : ModEntry.cs
License : GNU General Public License v3.0
Project Creator : aedenthorn

public static void Layer_Draw_Postfix(Layer __instance)
        {
            if (!config.EnableMod || Regex.IsMatch(__instance.Id, "[0-9]$"))
                return;

            foreach (Layer layer in Game1.currentLocation.Map.Layers)
            {
                Match match = Regex.Match(layer.Id, $"^{__instance.Id}([0-9]+)$");
                if (match.Success)
                {
                    thisLayerDepth = int.Parse(match.Groups[1].Value);
                    layer.Draw(Game1.mapDisplayDevice, Game1.viewport, Location.Origin, false, 4);
                    thisLayerDepth = 0;
                }
            }
        }

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

internal bool KillDenyHttpHeaders()
        {
            try
            {
                foreach (var head in RouteOption.Option.Security.DenyHttpHeaders)
                {
                    if (!Data.Headers.ContainsKey(head.Head))
                        continue;
                    switch (head.DenyType)
                    {
                        case DenyType.Hase:
                            if (Data.Headers.ContainsKey(head.Head))
                                return false;
                            break;
                        case DenyType.NonHase:
                            if (!Data.Headers.ContainsKey(head.Head))
                                return false;
                            break;
                        case DenyType.Count:
                            if (!Data.Headers.ContainsKey(head.Head))
                                break;
                            if (Data.Headers[head.Head].Count == int.Parse(head.Value))
                                return false;
                            break;
                        case DenyType.Equals:
                            if (!Data.Headers.ContainsKey(head.Head))
                                break;
                            if (string.Equals(Data.Headers[head.Head].ToString(), head.Value,
                                StringComparison.OrdinalIgnoreCase))
                                return false;
                            break;
                        case DenyType.Like:
                            if (!Data.Headers.ContainsKey(head.Head))
                                break;
                            if (Data.Headers[head.Head].ToString().Contains(head.Value))
                                return false;
                            break;
                        case DenyType.Regex:
                            if (!Data.Headers.ContainsKey(head.Head))
                                break;
                            var regx = new Regex(head.Value,
                                RegexOptions.IgnoreCase | RegexOptions.ECMAScript | RegexOptions.Multiline);
                            if (regx.IsMatch(Data.Headers[head.Head].ToString()))
                                return false;
                            break;
                    }
                }

                return true;
            }
            catch (Exception e)
            {
                LogRecorder.Exception(e);
                return true;
            }
        }

19 View Source File : AG0027EnsureOnlyDataSeleniumIsUsedToFindElements.cs
License : Apache License 2.0
Project Creator : 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([email protected]"""{constantValue.Value}"""))
            {
                context.ReportDiagnostic(Diagnostic.Create(Descriptor, firstArgument.GetLocation()));
            }
        }

19 View Source File : AG0005TestMethodNamesMustFollowConvention.cs
License : Apache License 2.0
Project Creator : agoda-com

private void replacedyzeNode(SyntaxNodereplacedysisContext context)
        {
            var methodDeclaration = (MethodDeclarationSyntax) context.Node;

            // ensure is test case 
            if (!TestMethodHelpers.IsTestCase(methodDeclaration, context))
            {
                return;
            }
            
            // ensure name is valid
            var methodName = methodDeclaration.Identifier.ValueText;
            if (MatchValidTestName.IsMatch(methodName))
            {
                return;
            }

            // report error at position of method name
            var methodNameToken = methodDeclaration.ChildTokens().First(t => t.IsKind(SyntaxKind.IdentifierToken));
            context.ReportDiagnostic(Diagnostic.Create(Descriptor, methodNameToken.GetLocation()));
        }

19 View Source File : MemoryCacheManager.cs
License : MIT License
Project Creator : ahmet-cetinkaya

public void RemoveByPattern(string pattern)
        {
            var cacheEntriesCollectionDefinition = typeof(MemoryCache).GetProperty("EntriesCollection",
                BindingFlags.NonPublic | BindingFlags.Instance);
            var cacheEntriesCollection = cacheEntriesCollectionDefinition.GetValue(_memoryCache) as dynamic;
            var cacheCollectionValues = new List<ICacheEntry>();

            foreach (var cacheItem in cacheEntriesCollection)
            {
                ICacheEntry cacheItemValue = cacheItem.GetType().GetProperty("Value").GetValue(cacheItem, null);
                cacheCollectionValues.Add(cacheItemValue);
            }

            var regex = new Regex(pattern, RegexOptions.Singleline | RegexOptions.Compiled | RegexOptions.IgnoreCase);
            var keysToRemove = cacheCollectionValues
                .Where(d => regex.IsMatch(d.Key.ToString()))
                .Select(d => d.Key)
                .ToList();

            foreach (var key in keysToRemove) _memoryCache.Remove(key);
        }

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

public virtual string ToCsv() {
			var f = new StringBuilder();
			var reg = new Regex("\n|\r|,|\"", RegexOptions.Compiled);

			// Field Names
			foreach (var field in FieldDefinitions.Select(t => t.Key))
				if (reg.IsMatch(field))
					f.Append("\"" + field.Replace("\"", "\"\"") + "\",");
				else
					f.Append(field + ",");

			if (f.Length == 0) {
				for (var i=0; i< FieldDatas.Count; ++i)
					f.AppendLine();
				return f.ToString();
			} else
				f.Length -= 1; // Remove ,
			f.AppendLine();

			foreach (var row in FieldDatas) {
				foreach (var col in row) {
					var s = col.ToString();
					if (reg.IsMatch(s))
						f.Append("\"" + s + "\",");
					else
						f.Append(s + ",");
				}
				f.Length -= 1; // Remove ,
				f.AppendLine();
			}
			f.Length -= 1; // Remove ,

			return f.ToString();
		}

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

private void FilterButton_Click(object sender, RoutedEventArgs e) {
            Tree.Items.Clear();
            ggpkContainer.FakeBundles2.Children.Clear();
            foreach (var f in ggpkContainer.Index.Files)
                if (RegexCheckBox.IsChecked.Value && Regex.IsMatch(f.path, FilterBox.Text) || !RegexCheckBox.IsChecked.Value && f.path.Contains(FilterBox.Text)) ggpkContainer.BuildBundleTree(f, ggpkContainer.FakeBundles2);
            var root = CreateNode(ggpkContainer.rootDirectory);
            Tree.Items.Add(root);
            root.IsSelected = true; // Clear view
            root.IsExpanded = true;
        }

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

public static void RecursiveFileList(RecordTreeNode record, string path, ICollection<KeyValuePair<IFileRecord, string>> list, bool export, string regex = null)
        {
            if (record is IFileRecord fr)
            {
                if ((export || File.Exists(path)) && (regex == null || Regex.IsMatch(record.GetPath(), regex)))
                    list.Add(new(fr, path));
            }
            else
                foreach (var f in record.Children)
                    RecursiveFileList(f, path + "\\" + f.Name, list, export, regex);
        }

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

public static void RecursiveFileList(RecordTreeNode record, ICollection<IFileRecord> list, string regex = null) {
            if (record is IFileRecord fr) {
                if (regex == null || Regex.IsMatch(record.GetPath(), regex))
                    list.Add(fr);
            } else
                foreach (var f in record.Children)
                    RecursiveFileList(f, list, regex);
        }

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

public virtual void GetFileList(string ROOTPath, ICollection<KeyValuePair<IFileRecord, string>> list, string searchPattern = "*", string regex = null) {
            var files = Directory.GetFiles(ROOTPath, searchPattern, SearchOption.AllDirectories);
            foreach (var f in files) {
                var path = f[(ROOTPath.Length + 1)..];
                if ((regex == null || Regex.IsMatch(path, regex)) && FindRecord(path) is IFileRecord ifr)
                    list.Add(new(ifr, f));
			}
        }

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

public virtual void GetFileListFromZip(IEnumerable<ZipArchiveEntry> ZipEntries, ICollection<KeyValuePair<IFileRecord, ZipArchiveEntry>> list, string regex = null) {
            var first = ZipEntries.FirstOrDefault();
            if (first == null)
                return;

            RecordTreeNode parent;
            if (first.FullName.StartsWith("ROOT/"))
                parent = rootDirectory;
            else if (first.FullName.StartsWith("Bundles2/"))
                parent = (RecordTreeNode)FakeBundles2 ?? OriginalBundles2;
            else
                throw new("The root directory in zip must be ROOT or Bundles2");

            var rootNameOffset = parent.Name.Length + 1;
            foreach (var zae in ZipEntries) {
                if (zae.FullName.EndsWith('/'))
                    continue;
                var path = zae.FullName[rootNameOffset..];
                if (regex == null || Regex.IsMatch(path, regex)) {
                    if (FindRecord(path, parent) is not IFileRecord ifr)
                        throw new Exception("Not found in GGPK: " + zae.FullName);
                    list.Add(new(ifr, zae));
                }
			}
        }

19 View Source File : EmailValidator.cs
License : MIT License
Project Creator : aishang2015

protected override bool IsValid(PropertyValidatorContext context)
        {
            var email = context.PropertyValue?.ToString();

            // 正则验证
            return Regex.IsMatch(email, _emailPattern);
        }

19 View Source File : IPValidator.cs
License : MIT License
Project Creator : aishang2015

protected override bool IsValid(PropertyValidatorContext context)
        {
            var ipAddress = context.PropertyValue?.ToString();

            // 正则验证
            return Regex.IsMatch(ipAddress, _ipPattern);
        }

19 View Source File : NumberValidator.cs
License : MIT License
Project Creator : aishang2015

protected override bool IsValid(PropertyValidatorContext context)
        {
            var number = context.PropertyValue?.ToString();

            // 正则验证
            return Regex.IsMatch(number, _numberPattern);
        }

19 View Source File : PhoneNumberValidator.cs
License : MIT License
Project Creator : aishang2015

protected override bool IsValid(PropertyValidatorContext context)
        {
            var phoneNumber = context.PropertyValue?.ToString();

            // 正则验证
            return Regex.IsMatch(phoneNumber, _phonePattern);
        }

19 View Source File : PostcodeValidator.cs
License : MIT License
Project Creator : aishang2015

protected override bool IsValid(PropertyValidatorContext context)
        {
            var postcode = context.PropertyValue?.ToString();

            // 正则验证
            return Regex.IsMatch(postcode, @"\d{6}");
        }

19 View Source File : UrlValidator.cs
License : MIT License
Project Creator : aishang2015

protected override bool IsValid(PropertyValidatorContext context)
        {
            var url = context.PropertyValue?.ToString();

            // 正则验证
            return Regex.IsMatch(url, _urlPattern);
        }

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

static bool UrlSuccess(WWW www)
	{
		if (!string.IsNullOrEmpty(www.error))
			return false;
		if (Regex.IsMatch(www.text, "404 not found", RegexOptions.IgnoreCase))
			return false;
		return true;
	}

19 View Source File : MenuHelperViewPages.cs
License : MIT License
Project Creator : akasarto

public T IfActiveItem<T>(string key, T thenTrueResult, T elseFalseResult = default(T))
		{
			var menuData = _htmlHelper.ViewContext.HttpContext.Items[nameof(MenuData)] as MenuData;

			if (menuData == null)
			{
				menuData = new MenuData();
			}

			var result = menuData.Items.Any(i => Regex.IsMatch(i, key, RegexOptions.IgnoreCase)) ? thenTrueResult : elseFalseResult;

			return result;
		}

19 View Source File : FileCollector.cs
License : MIT License
Project Creator : AkiniKites

private List<T> LoadInternal()
        {
            if (_useCache && _cache.TryLoadCache(out var cached))
            {
                if (cached.Any())
                    return cached;
            }
            else
            {
                cached = new List<T>();
            }

            var files = Prefetch.Load().Files.Keys;
            var bag = new ConcurrentBag<T>();

            var parallels = IoC.CmdOptions.SingleThread ? 1 : Environment.ProcessorCount;
            var tasks = new ParallelTasks<string>(
                parallels, file =>
                {
                    if (_fileNameValidator(file) && !_ignored.Any(x => x.IsMatch(file)))
                    {
                        foreach (var item in _itemGetter(file))
                            bag.Add(item);
                    }
                });

            tasks.Start();
            tasks.AddItems(files);
            tasks.WaitForComplete();

            GC.Collect();

            var itemList = bag.ToList();
            if (_consolidator != null)
                itemList = _consolidator(itemList).ToList();

            if (_useCache)
            {
                cached.AddRange(itemList);
                _cache.Save(cached);
            }

            return itemList;
        }

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

private static TrackInfo GetTrackInfos(Note[] notes, TrackChunk i, int index)
    {
        var eventsCollection = i.Events;
        var TrackNameEventsText = eventsCollection.OfType<SequenceTrackNameEvent>().Select(j => j.Text.Replace("\0", string.Empty).Trim()).Distinct().ToArray();
        var TrackName = TrackNameEventsText.FirstOrDefault() ?? "Unreplacedled";
        var IsProgramControlled = Regex.IsMatch(TrackName, @"^Program:.+$", RegexOptions.Compiled | RegexOptions.IgnoreCase);

        var timedNoteOffEvent = notes.LastOrDefault()?.GetTimedNoteOffEvent();
        return new TrackInfo
        {
            //TextEventsText = eventsCollection.OfType<TextEvent>().Select(j => j.Text.Replace("\0", string.Empty).Trim()).Distinct().ToArray(),
            ProgramChangeEventsText = eventsCollection.OfType<ProgramChangeEvent>().Select(j => $"channel {j.Channel}, {j.GetGMProgramName()}").Distinct().ToArray(),
            TrackNameEventsText = TrackNameEventsText,
            HighestNote = notes.MaxElement(j => (int)j.NoteNumber),
            LowestNote = notes.MinElement(j => (int)j.NoteNumber),
            NoteCount = notes.Length,
            DurationMetric = timedNoteOffEvent?.TimeAs<MetricTimeSpan>(CurrentTMap) ?? new MetricTimeSpan(),
            DurationMidi = timedNoteOffEvent?.Time ?? 0,
            TrackName = TrackName,
            IsProgramControlled = IsProgramControlled,
            Index = index
        };
    }

19 View Source File : ClstWatcher.cs
License : MIT License
Project Creator : akpaevj

private Dictionary<string, (string Name, string DataBaseName)> ReadInfoBases()
        {
            var items = new Dictionary<string, (string, string)>();

            var fileData = File.ReadAllText(_path);
            var parsedData = BracketsParser.ParseBlock(fileData);

            var infoBasesNode = parsedData[2];
            int count = infoBasesNode[0];

            if (count > 0)
                for (var i = 1; i <= count; i++)
                {
                    var infoBaseNode = infoBasesNode[i];

                    var elPath = Path.Combine(_folder, infoBaseNode[0]);
                    string name = infoBaseNode[5];

                    foreach (var template in _templates)
                        if (Regex.IsMatch(name, template.Mask))
                        {
                            var dataBaseName = template.Template.Replace("[IBNAME]", name);
                            items.Add(elPath, (name, dataBaseName));

                            break;
                        }
                }

            return items;
        }

19 View Source File : PropertyExpressionBuilder.cs
License : MIT License
Project Creator : alethic

static bool AdditionalProperties(JSchema schema, JObject o, Func<JToken, bool> additionalPropertiesSchema)
        {
            foreach (var p in o.Properties())
                if (schema.Properties.ContainsKey(p.Name) == false &&
                    schema.PatternProperties.Any(i => Regex.IsMatch(p.Name, i.Key)) == false)
                    if (additionalPropertiesSchema(p.Value) == false)
                        return false;

            return true;
        }

19 View Source File : PropertyExpressionBuilder.cs
License : MIT License
Project Creator : alethic

static bool AllowAdditionalProperties(JSchema schema, JObject o)
        {
            foreach (var p in o.Properties())
                if (schema.Properties.ContainsKey(p.Name) == false &&
                    schema.PatternProperties.Any(i => Regex.IsMatch(p.Name, i.Key)) == false)
                    return false;

            return true;
        }

19 View Source File : PropertyExpressionBuilder.cs
License : MIT License
Project Creator : alethic

static bool PatternProperty(string propertyPattern, Func<JToken, bool> propertySchema, JObject o)
        {
            foreach (var p in o.Properties())
                if (Regex.IsMatch(p.Name, propertyPattern))
                    if (!propertySchema(p.Value))
                        return false;

            return true;
        }

19 View Source File : MessageUtils.cs
License : GNU General Public License v3.0
Project Creator : alexdillon

public static bool IsReplyGen1(Message message)
        {
            return !string.IsNullOrEmpty(message.Text) && Regex.IsMatch(message.Text, RepliedMessageRegex);
        }

19 View Source File : MessageControlViewModel.cs
License : GNU General Public License v3.0
Project Creator : alexdillon

private void HandleLinkBasedAttachments()
        {
            // Load Link-Based Attachments (Tweets, Web Images, Websites, etc.)
            var text = this.Message.Text ?? string.Empty;
            if (text.IndexOf(" ") > 0)
            {
                // Use IndexOf instead of Contains to prevent issues with strange unicode characters.
                // only look to see if the first chunk is a URL
                text = text.Substring(0, text.IndexOf(" "));
            }

            const string TwitterPrefixHttps = "https://twitter.com/";
            const string TwitterPrefixHttp = "http://twitter.com/";

            const string GroupMeImageRegexHttps = @"https:\/\/i.groupme.com\/[0-99999]*x[0-99999]*\..*";

            string[] imageExtensions = { "png", "jpg", "jpeg", "gif", "bmp" };

            const string WebPrefixHttps = "https://";
            const string WebPrefixHttp = "http://";

            IHidesTextAttachment vm;

            var linkExtension = text.Split('.').LastOrDefault();

            if (text.StartsWith(TwitterPrefixHttps) || text.StartsWith(TwitterPrefixHttp))
            {
                vm = new TwitterAttachmentControlViewModel(text, this.Message.ImageDownloader);
                this.AttachedItems.Add(vm);
            }
            else if (imageExtensions.Contains(linkExtension) && Uri.TryCreate(text, UriKind.Absolute, out var _))
            {
                vm = new ImageLinkAttachmentControlViewModel(text, this.Message.ImageDownloader);
                this.AttachedItems.Add(vm);
            }
            else if (Regex.IsMatch(text, GroupMeImageRegexHttps))
            {
                var groupMeIUrl = Regex.Match(text, GroupMeImageRegexHttps).Value;
                vm = new ImageLinkAttachmentControlViewModel(groupMeIUrl, this.Message.ImageDownloader);
                this.AttachedItems.Add(vm);
            }
            else if (text.StartsWith(WebPrefixHttps) || text.StartsWith(WebPrefixHttp))
            {
                vm = new GenericLinkAttachmentControlViewModel(text, this.Message.ImageDownloader);
                this.AttachedItems.Add(vm);
            }
            else
            {
                return;
            }

            if (!string.IsNullOrEmpty(vm.HiddenText))
            {
                this.HiddenText = vm.HiddenText + this.HiddenText;
            }
        }

19 View Source File : MessageControlViewModel.cs
License : GNU General Public License v3.0
Project Creator : alexdillon

private List<Inline> ProcessHyperlinks(Run run)
        {
            var result = new List<Inline>();
            var text = run.Text;

            while (true)
            {
                if (!Regex.IsMatch(text, RegexUtils.UrlRegex))
                {
                    // no URLs contained
                    result.Add(new Run(text));
                    break;
                }
                else
                {
                    // url is contained in the input string
                    var match = Regex.Match(text, Utilities.RegexUtils.UrlRegex);

                    if (match.Index > 0)
                    {
                        // convert the leading text to a Run
                        result.Add(new Run(text.Substring(0, match.Index)));
                    }

                    try
                    {
                        var navigableUrl = match.Value;

                        if (navigableUrl.EndsWith("))"))
                        {
                            // URLs almost never end in )). This is typically a case where an entire URL containing a ) is wrapped in parenthesis.
                            // Trim the closing parenthesis.
                            navigableUrl = navigableUrl.Substring(0, navigableUrl.Length - 1);

                            result.Add(this.MakeHyperLink(navigableUrl));
                            result.Add(new Run(")"));
                        }
                        else if (navigableUrl.EndsWith(")") && !navigableUrl.Contains("("))
                        {
                            // It's extremely uncommon for a URL to contain a ) without a matching (.
                            // This is most likely caused by the entire URL being contained in parenthesis, and should be stripped.
                            navigableUrl = navigableUrl.Substring(0, navigableUrl.Length - 1);

                            result.Add(this.MakeHyperLink(navigableUrl));
                            result.Add(new Run(")"));
                        }
                        else
                        {
                            // Normal URL with no strange parenthesis to handle
                            result.Add(this.MakeHyperLink(navigableUrl));
                        }
                    }
                    catch (Exception)
                    {
                        // Some super strange URLs preplaced the regex, but fail
                        // to decode correctly. Ignore if this happens.
                        result.Add(new Run(match.Value));
                    }

                    // Keep looping over the rest of the string.
                    text = text.Substring(match.Index + match.Length);
                }
            }

            return result;
        }

19 View Source File : MessageControlViewModel.cs
License : GNU General Public License v3.0
Project Creator : alexdillon

private void LoadAttachments()
        {
            bool hasMultipleImages = this.Message.Attachments.OfType<ImageAttachment>().Count() > 1;

            // Load GroupMe Image and Video Attachments
            foreach (var attachment in this.Message.Attachments)
            {
                if (attachment is ImageAttachment imageAttach)
                {
                    var displayMode = GroupMeImageAttachmentControlViewModel.GroupMeImageDisplayMode.Large;
                    if (hasMultipleImages && this.ShowPreviewsOnlyForMultiImages)
                    {
                        displayMode = GroupMeImageAttachmentControlViewModel.GroupMeImageDisplayMode.Preview;
                    }

                    var imageVm = new GroupMeImageAttachmentControlViewModel(imageAttach, this.Message.ImageDownloader, displayMode);
                    this.AttachedItems.Add(imageVm);

                    // Starting in 9/2019, GroupMe supports multiple images-per-message.
                }
                else if (attachment is LinkedImageAttachment linkedImage)
                {
                    var imageLinkVm = new ImageLinkAttachmentControlViewModel(linkedImage.Url, this.Message.ImageDownloader, this.Message.Text);
                    this.AttachedItems.Add(imageLinkVm);

                    // Linked Images can't have captions, so hide the entire body
                    this.HiddenText = this.Message.Text;

                    // Don't allow any other attachment types to be included if a linked_image is.
                    return;
                }
                else if (attachment is VideoAttachment videoAttach)
                {
                    var videoLinkedVm = new VideoAttachmentControlViewModel(videoAttach, this.Message.ImageDownloader);
                    this.AttachedItems.Add(videoLinkedVm);

                    // Videos can have captions, so only exclude the v.groupme url from the body
                    this.HiddenText = videoAttach.Url;

                    // Don't allow any other attachment types to be included if a video is.
                    return;
                }
                else if (attachment is FileAttachment fileAttach)
                {
                    var container = (IMessageContainer)this.Message.Group ?? (IMessageContainer)this.Message.Chat;
                    var doreplacedentVm = new FileAttachmentControlViewModel(fileAttach, container);
                    this.AttachedItems.Add(doreplacedentVm);

                    // Videos can have captions, so only exclude the share url from the body
                    if (this.Message.Text.Contains(" - Shared a doreplacedent"))
                    {
                        this.HiddenText = this.Message.Text.Substring(this.Message.Text.LastIndexOf(" - Shared a doreplacedent"));
                    }
                    else
                    {
                        this.HiddenText = this.Message.Text.Substring(this.Message.Text.LastIndexOf("Shared a doreplacedent"));
                    }

                    // Don't allow any other attachment types to be included if a video is.
                    return;
                }
            }

            // Load Link-Based Attachments (Tweets, Web Images, Websites, etc.)
            var text = this.Message.Text ?? string.Empty;
            if (text.Contains(" "))
            {
                // only look to see if the first chunk is a URL
                text = text.Substring(0, text.IndexOf(" "));
            }

            const string TwitterPrefixHttps = "https://twitter.com/";
            const string TwitterPrefixHttp = "http://twitter.com/";

            const string GroupMeImageRegexHttps = @"https:\/\/i.groupme.com\/[0-99999]*x[0-99999]*\..*";

            string[] imageExtensions = { "png", "jpg", "jpeg", "gif", "bmp" };

            const string WebPrefixHttps = "https://";
            const string WebPrefixHttp = "http://";

            LinkAttachmentBaseViewModel vm;

            var linkExtension = text.Split('.').LastOrDefault();

            if (text.StartsWith(TwitterPrefixHttps) || text.StartsWith(TwitterPrefixHttp))
            {
                vm = new TwitterAttachmentControlViewModel(text, this.Message.ImageDownloader);
                this.AttachedItems.Add(vm);
            }
            else if (imageExtensions.Contains(linkExtension))
            {
                vm = new ImageLinkAttachmentControlViewModel(text, this.Message.ImageDownloader);
                this.AttachedItems.Add(vm);
            }
            else if (Regex.IsMatch(text, GroupMeImageRegexHttps))
            {
                var groupMeIUrl = Regex.Match(text, GroupMeImageRegexHttps).Value;
                vm = new ImageLinkAttachmentControlViewModel(groupMeIUrl, this.Message.ImageDownloader);
                this.AttachedItems.Add(vm);
            }
            else if (text.StartsWith(WebPrefixHttps) || text.StartsWith(WebPrefixHttp))
            {
                vm = new GenericLinkAttachmentControlViewModel(text, this.Message.ImageDownloader);
                this.AttachedItems.Add(vm);
            }
            else
            {
                return;
            }

            if (vm.Uri != null)
            {
                this.HiddenText = vm.Url;
            }
        }

19 View Source File : ClassTypeEditor.cs
License : GNU General Public License v3.0
Project Creator : alexgracianoarj

private bool ValidateNHMTableName()
        {
            if (NeedValidation)
            {
                try
                {
                    if (string.IsNullOrEmpty(txtNHMTableName.Text))
                    {
                        Shape.CompositeType.NHMTableName = null;
                    }
                    else
                    {
                        if ((new System.Text.RegularExpressions.Regex("[^a-zA-Z0-9_ ]").IsMatch(txtNHMTableName.Text)))
                            throw new BadSyntaxException("Invalid NHM Table Name");

                        Shape.CompositeType.NHMTableName = txtNHMTableName.Text;
                    }
                    RefreshValues();
                }
                catch (BadSyntaxException ex)
                {
                    SetError(ex.Message);
                    return false;
                }
            }
            return true;
        }

19 View Source File : TorrentInfoTest.cs
License : MIT License
Project Creator : aljazsim

[TestMethod]
        public void TorrentInfo_TryLoad()
        {
            TorrentInfo info;
            string filePath;
            Regex regex = new Regex("[a-zA-Z0-9+/=]{28}", RegexOptions.Compiled);
            int i = 0;

            filePath = @"..\..\..\TorrentClientTest.Data\Torrent1.torrent";

            // multi file
            if (TorrentInfo.TryLoad(filePath, out info))
            {
                replacedert.AreEqual(1, info.AnnounceList.Count());
                replacedert.AreEqual("http://192.168.1.2:4009/announce", info.AnnounceList.ElementAt(0).AbsoluteUri);
                replacedert.AreEqual(null, info.Comment);
                replacedert.AreEqual("uTorrent/3320", info.CreatedBy);
                replacedert.AreEqual(new DateTime(2014, 1, 26, 16, 1, 33), info.CreationDate);
                replacedert.AreEqual(Encoding.ASCII, info.Encoding);
                replacedert.AreEqual(36, info.Files.Count());
                replacedert.AreEqual(info.Length, info.Files.Sum(x => x.Length));
                replacedert.AreEqual(16384, info.BlockLength);
                replacedert.AreEqual(4, info.BlocksCount);
                replacedert.AreEqual(info.PieceLength / info.BlockLength, info.BlocksCount);
                replacedert.AreEqual(772, info.PiecesCount);
                replacedert.AreEqual(65536, info.PieceLength);
                replacedert.AreEqual(true, info.IsPrivate);
                replacedert.AreEqual(772, info.PieceHashes.Count());

                replacedert.AreEqual(true, info.Files.ElementAt(i).Download);
                replacedert.AreEqual(@"Torrent1\0", info.Files.ElementAt(i).FilePath);
                replacedert.AreEqual(2946749, info.Files.ElementAt(i).Length);
                replacedert.AreEqual(null, info.Files.ElementAt(i).Md5Hash);

                replacedert.AreEqual(true, info.Files.ElementAt(++i).Download);
                replacedert.AreEqual(@"Torrent1\1", info.Files.ElementAt(i).FilePath);
                replacedert.AreEqual(179587, info.Files.ElementAt(i).Length);
                replacedert.AreEqual(null, info.Files.ElementAt(i).Md5Hash);

                replacedert.AreEqual(true, info.Files.ElementAt(++i).Download);
                replacedert.AreEqual(@"Torrent1\2", info.Files.ElementAt(i).FilePath);
                replacedert.AreEqual(2994660, info.Files.ElementAt(i).Length);
                replacedert.AreEqual(null, info.Files.ElementAt(i).Md5Hash);

                replacedert.AreEqual(true, info.Files.ElementAt(++i).Download);
                replacedert.AreEqual(@"Torrent1\3", info.Files.ElementAt(i).FilePath);
                replacedert.AreEqual(106194, info.Files.ElementAt(i).Length);
                replacedert.AreEqual(null, info.Files.ElementAt(i).Md5Hash);

                replacedert.AreEqual(true, info.Files.ElementAt(++i).Download);
                replacedert.AreEqual(@"Torrent1\4", info.Files.ElementAt(i).FilePath);
                replacedert.AreEqual(993456, info.Files.ElementAt(i).Length);
                replacedert.AreEqual(null, info.Files.ElementAt(i).Md5Hash);

                replacedert.AreEqual(true, info.Files.ElementAt(++i).Download);
                replacedert.AreEqual(@"Torrent1\5", info.Files.ElementAt(i).FilePath);
                replacedert.AreEqual(44557, info.Files.ElementAt(i).Length);
                replacedert.AreEqual(null, info.Files.ElementAt(i).Md5Hash);

                replacedert.AreEqual(true, info.Files.ElementAt(++i).Download);
                replacedert.AreEqual(@"Torrent1\6", info.Files.ElementAt(i).FilePath);
                replacedert.AreEqual(355807, info.Files.ElementAt(i).Length);
                replacedert.AreEqual(null, info.Files.ElementAt(i).Md5Hash);

                replacedert.AreEqual(true, info.Files.ElementAt(++i).Download);
                replacedert.AreEqual(@"Torrent1\7", info.Files.ElementAt(i).FilePath);
                replacedert.AreEqual(518967, info.Files.ElementAt(i).Length);
                replacedert.AreEqual(null, info.Files.ElementAt(i).Md5Hash);

                replacedert.AreEqual(true, info.Files.ElementAt(++i).Download);
                replacedert.AreEqual(@"Torrent1\8", info.Files.ElementAt(i).FilePath);
                replacedert.AreEqual(1672937, info.Files.ElementAt(i).Length);
                replacedert.AreEqual(null, info.Files.ElementAt(i).Md5Hash);

                replacedert.AreEqual(true, info.Files.ElementAt(++i).Download);
                replacedert.AreEqual(@"Torrent1\9", info.Files.ElementAt(i).FilePath);
                replacedert.AreEqual(8001, info.Files.ElementAt(i).Length);
                replacedert.AreEqual(null, info.Files.ElementAt(i).Md5Hash);

                replacedert.AreEqual(true, info.Files.ElementAt(++i).Download);
                replacedert.AreEqual(@"Torrent1\a", info.Files.ElementAt(i).FilePath);
                replacedert.AreEqual(1352543, info.Files.ElementAt(i).Length);
                replacedert.AreEqual(null, info.Files.ElementAt(i).Md5Hash);

                replacedert.AreEqual(true, info.Files.ElementAt(++i).Download);
                replacedert.AreEqual(@"Torrent1\b", info.Files.ElementAt(i).FilePath);
                replacedert.AreEqual(62629, info.Files.ElementAt(i).Length);
                replacedert.AreEqual(null, info.Files.ElementAt(i).Md5Hash);

                replacedert.AreEqual(true, info.Files.ElementAt(++i).Download);
                replacedert.AreEqual(@"Torrent1\c", info.Files.ElementAt(i).FilePath);
                replacedert.AreEqual(2052729, info.Files.ElementAt(i).Length);
                replacedert.AreEqual(null, info.Files.ElementAt(i).Md5Hash);

                replacedert.AreEqual(true, info.Files.ElementAt(++i).Download);
                replacedert.AreEqual(@"Torrent1\d", info.Files.ElementAt(i).FilePath);
                replacedert.AreEqual(5583717, info.Files.ElementAt(i).Length);
                replacedert.AreEqual(null, info.Files.ElementAt(i).Md5Hash);

                replacedert.AreEqual(true, info.Files.ElementAt(++i).Download);
                replacedert.AreEqual(@"Torrent1\e", info.Files.ElementAt(i).FilePath);
                replacedert.AreEqual(2630552, info.Files.ElementAt(i).Length);
                replacedert.AreEqual(null, info.Files.ElementAt(i).Md5Hash);

                replacedert.AreEqual(true, info.Files.ElementAt(++i).Download);
                replacedert.AreEqual(@"Torrent1\f", info.Files.ElementAt(i).FilePath);
                replacedert.AreEqual(72133, info.Files.ElementAt(i).Length);
                replacedert.AreEqual(null, info.Files.ElementAt(i).Md5Hash);

                replacedert.AreEqual(true, info.Files.ElementAt(++i).Download);
                replacedert.AreEqual(@"Torrent1\g", info.Files.ElementAt(i).FilePath);
                replacedert.AreEqual(999736, info.Files.ElementAt(i).Length);
                replacedert.AreEqual(null, info.Files.ElementAt(i).Md5Hash);

                replacedert.AreEqual(true, info.Files.ElementAt(++i).Download);
                replacedert.AreEqual(@"Torrent1\h", info.Files.ElementAt(i).FilePath);
                replacedert.AreEqual(510815, info.Files.ElementAt(i).Length);
                replacedert.AreEqual(null, info.Files.ElementAt(i).Md5Hash);

                replacedert.AreEqual(true, info.Files.ElementAt(++i).Download);
                replacedert.AreEqual(@"Torrent1\i", info.Files.ElementAt(i).FilePath);
                replacedert.AreEqual(155862, info.Files.ElementAt(i).Length);
                replacedert.AreEqual(null, info.Files.ElementAt(i).Md5Hash);

                replacedert.AreEqual(true, info.Files.ElementAt(++i).Download);
                replacedert.AreEqual(@"Torrent1\j", info.Files.ElementAt(i).FilePath);
                replacedert.AreEqual(207147, info.Files.ElementAt(i).Length);
                replacedert.AreEqual(null, info.Files.ElementAt(i).Md5Hash);

                replacedert.AreEqual(true, info.Files.ElementAt(++i).Download);
                replacedert.AreEqual(@"Torrent1\k", info.Files.ElementAt(i).FilePath);
                replacedert.AreEqual(75435, info.Files.ElementAt(i).Length);
                replacedert.AreEqual(null, info.Files.ElementAt(i).Md5Hash);

                replacedert.AreEqual(true, info.Files.ElementAt(++i).Download);
                replacedert.AreEqual(@"Torrent1\l", info.Files.ElementAt(i).FilePath);
                replacedert.AreEqual(6274678, info.Files.ElementAt(i).Length);
                replacedert.AreEqual(null, info.Files.ElementAt(i).Md5Hash);

                replacedert.AreEqual(true, info.Files.ElementAt(++i).Download);
                replacedert.AreEqual(@"Torrent1\m", info.Files.ElementAt(i).FilePath);
                replacedert.AreEqual(1574206, info.Files.ElementAt(i).Length);
                replacedert.AreEqual(null, info.Files.ElementAt(i).Md5Hash);

                replacedert.AreEqual(true, info.Files.ElementAt(++i).Download);
                replacedert.AreEqual(@"Torrent1\n", info.Files.ElementAt(i).FilePath);
                replacedert.AreEqual(1834856, info.Files.ElementAt(i).Length);
                replacedert.AreEqual(null, info.Files.ElementAt(i).Md5Hash);

                replacedert.AreEqual(true, info.Files.ElementAt(++i).Download);
                replacedert.AreEqual(@"Torrent1\o", info.Files.ElementAt(i).FilePath);
                replacedert.AreEqual(13675, info.Files.ElementAt(i).Length);
                replacedert.AreEqual(null, info.Files.ElementAt(i).Md5Hash);

                replacedert.AreEqual(true, info.Files.ElementAt(++i).Download);
                replacedert.AreEqual(@"Torrent1\p", info.Files.ElementAt(i).FilePath);
                replacedert.AreEqual(1004240, info.Files.ElementAt(i).Length);
                replacedert.AreEqual(null, info.Files.ElementAt(i).Md5Hash);

                replacedert.AreEqual(true, info.Files.ElementAt(++i).Download);
                replacedert.AreEqual(@"Torrent1\q", info.Files.ElementAt(i).FilePath);
                replacedert.AreEqual(3106766, info.Files.ElementAt(i).Length);
                replacedert.AreEqual(null, info.Files.ElementAt(i).Md5Hash);

                replacedert.AreEqual(true, info.Files.ElementAt(++i).Download);
                replacedert.AreEqual(@"Torrent1\r", info.Files.ElementAt(i).FilePath);
                replacedert.AreEqual(1009289, info.Files.ElementAt(i).Length);
                replacedert.AreEqual(null, info.Files.ElementAt(i).Md5Hash);

                replacedert.AreEqual(true, info.Files.ElementAt(++i).Download);
                replacedert.AreEqual(@"Torrent1\s", info.Files.ElementAt(i).FilePath);
                replacedert.AreEqual(3207364, info.Files.ElementAt(i).Length);
                replacedert.AreEqual(null, info.Files.ElementAt(i).Md5Hash);

                replacedert.AreEqual(true, info.Files.ElementAt(++i).Download);
                replacedert.AreEqual(@"Torrent1\t", info.Files.ElementAt(i).FilePath);
                replacedert.AreEqual(66021, info.Files.ElementAt(i).Length);
                replacedert.AreEqual(null, info.Files.ElementAt(i).Md5Hash);

                replacedert.AreEqual(true, info.Files.ElementAt(++i).Download);
                replacedert.AreEqual(@"Torrent1\u", info.Files.ElementAt(i).FilePath);
                replacedert.AreEqual(3492239, info.Files.ElementAt(i).Length);
                replacedert.AreEqual(null, info.Files.ElementAt(i).Md5Hash);

                replacedert.AreEqual(true, info.Files.ElementAt(++i).Download);
                replacedert.AreEqual(@"Torrent1\v", info.Files.ElementAt(i).FilePath);
                replacedert.AreEqual(200822, info.Files.ElementAt(i).Length);
                replacedert.AreEqual(null, info.Files.ElementAt(i).Md5Hash);

                replacedert.AreEqual(true, info.Files.ElementAt(++i).Download);
                replacedert.AreEqual(@"Torrent1\w", info.Files.ElementAt(i).FilePath);
                replacedert.AreEqual(2077420, info.Files.ElementAt(i).Length);
                replacedert.AreEqual(null, info.Files.ElementAt(i).Md5Hash);

                replacedert.AreEqual(true, info.Files.ElementAt(++i).Download);
                replacedert.AreEqual(@"Torrent1\x", info.Files.ElementAt(i).FilePath);
                replacedert.AreEqual(2170102, info.Files.ElementAt(i).Length);
                replacedert.AreEqual(null, info.Files.ElementAt(i).Md5Hash);

                replacedert.AreEqual(true, info.Files.ElementAt(++i).Download);
                replacedert.AreEqual(@"Torrent1\y", info.Files.ElementAt(i).FilePath);
                replacedert.AreEqual(159041, info.Files.ElementAt(i).Length);
                replacedert.AreEqual(null, info.Files.ElementAt(i).Md5Hash);

                replacedert.AreEqual(true, info.Files.ElementAt(++i).Download);
                replacedert.AreEqual(@"Torrent1\z", info.Files.ElementAt(i).FilePath);
                replacedert.AreEqual(877610, info.Files.ElementAt(i).Length);
                replacedert.AreEqual(null, info.Files.ElementAt(i).Md5Hash);

                foreach (var hash in info.PieceHashes)
                {
                    replacedert.IsTrue(regex.IsMatch(hash));
                }
            }
            else
            {
                replacedert.Fail($"Could not parse torrent file {filePath}");
            }
        }

19 View Source File : TorrentInfoTest.cs
License : MIT License
Project Creator : aljazsim

[TestMethod]
        public void TorrentInfo_TryLoad2()
        {
            TorrentInfo info;
            string filePath;
            Regex regex = new Regex("[a-zA-Z0-9+/=]{28}", RegexOptions.Compiled);
            int i = 0;

            filePath = @"..\..\..\TorrentClientTest.Data\Torrent2.torrent";

            // single file
            if (TorrentInfo.TryLoad(filePath, out info))
            {
                replacedert.AreEqual(1, info.AnnounceList.Count());
                replacedert.AreEqual("http://192.168.1.2:4009/announce", info.AnnounceList.ElementAt(0).AbsoluteUri);
                replacedert.AreEqual(null, info.Comment);
                replacedert.AreEqual("uTorrent/3320", info.CreatedBy);
                replacedert.AreEqual(new DateTime(2014, 1, 25, 12, 16, 44), info.CreationDate);
                replacedert.AreEqual(Encoding.ASCII, info.Encoding);
                replacedert.AreEqual(1, info.Files.Count());
                replacedert.AreEqual(info.Length, info.Files.Sum(x => x.Length));
                replacedert.AreEqual(16384, info.BlockLength);
                replacedert.AreEqual(64, info.BlocksCount);
                replacedert.AreEqual(info.PieceLength / info.BlockLength, info.BlocksCount);
                replacedert.AreEqual(700, info.PiecesCount);
                replacedert.AreEqual(1048576, info.PieceLength);
                replacedert.AreEqual(true, info.IsPrivate);
                replacedert.AreEqual(700, info.PieceHashes.Count());

                replacedert.AreEqual(true, info.Files.ElementAt(i).Download);
                replacedert.AreEqual(@"Torrent2\a", info.Files.ElementAt(i).FilePath);
                replacedert.AreEqual(734003200, info.Files.ElementAt(i).Length);
                replacedert.AreEqual(null, info.Files.ElementAt(i).Md5Hash);

                foreach (var hash in info.PieceHashes)
                {
                    replacedert.IsTrue(regex.IsMatch(hash));
                }
            }
            else
            {
                replacedert.Fail($"Could not parse torrent file {filePath}.");
            }
        }

19 View Source File : AllureTestTracerWrapper.cs
License : Apache License 2.0
Project Creator : allure-framework

private void StartStep(StepInstance stepInstance)
        {
            var stepResult = new StepResult
            {
                name = $"{stepInstance.Keyword} {stepInstance.Text}"
            };


            // parse MultilineTextArgument
            if (stepInstance.MultilineTextArgument != null)
                allure.AddAttachment(
                    "multiline argument",
                    "text/plain",
                    Encoding.ASCII.GetBytes(stepInstance.MultilineTextArgument),
                    ".txt");

            var table = stepInstance.TableArgument;
            var isTableProcessed = table == null;

            // parse table as step params
            if (table != null)
            {
                var header = table.Header.ToArray();
                if (pluginConfiguration.stepArguments.convertToParameters)
                {
                    var parameters = new List<Parameter>();

                    // convert 2 column table into param-value
                    if (table.Header.Count == 2)
                    {
                        var paramNameMatch = Regex.IsMatch(header[0], pluginConfiguration.stepArguments.paramNameRegex);
                        var paramValueMatch =
                            Regex.IsMatch(header[1], pluginConfiguration.stepArguments.paramValueRegex);
                        if (paramNameMatch && paramValueMatch)
                        {
                            for (var i = 0; i < table.RowCount; i++)
                                parameters.Add(new Parameter {name = table.Rows[i][0], value = table.Rows[i][1]});

                            isTableProcessed = true;
                        }
                    }
                    // add step params for 1 row table
                    else if (table.RowCount == 1)
                    {
                        for (var i = 0; i < table.Header.Count; i++)
                            parameters.Add(new Parameter {name = header[i], value = table.Rows[0][i]});
                        isTableProcessed = true;
                    }

                    stepResult.parameters = parameters;
                }
            }

            allure.StartStep(PluginHelper.NewId(), stepResult);

            // add csv table for multi-row table if was not processed as params already
            if (isTableProcessed) return;
            using var sw = new StringWriter();
            using var csv = new CsvWriter(sw, CultureInfo.InvariantCulture);
            foreach (var item in table.Header) csv.WriteField(item);
            csv.NextRecord();
            foreach (var row in table.Rows)
            {
                foreach (var item in row.Values) csv.WriteField(item);
                csv.NextRecord();
            }

            allure.AddAttachment("table", "text/csv",
                Encoding.ASCII.GetBytes(sw.ToString()), ".csv");
        }

19 View Source File : IpEntry.cs
License : MIT License
Project Creator : AndreiMisiukevich

private void OnEntryChanged(object sender, EventArgs e)
        {
            var ipEntry = (IpEntry) sender;
            var entryText = ipEntry.Text;
            if (entryText != _previousTextValue)
            {
                if (!_ipRegex.IsMatch(entryText))
                {
                    ipEntry.Text = _previousTextValue;
                }
            }

            _previousTextValue = entryText;
        }

See More Examples