// GET: Test public ActionResult Index() { var es = new EmailService(); var datasetId = 1; var title = "my cool dataset"; es.Send(MessageHelper.GetCreateDatasetHeader(), MessageHelper.GetCreateDatasetMessage(datasetId, title, "David Schöne"), ConfigurationManager.AppSettings["SystemEmail"] ); string name = "test"; var x = RegExHelper.IsFilenameValid(name); name = "test | filename"; x = RegExHelper.IsFilenameValid(name); name = RegExHelper.GetCleanedFilename(name); name = "des<>"; x = RegExHelper.IsFilenameValid(name); name = RegExHelper.GetCleanedFilename(name); name = "123\""; x = RegExHelper.IsFilenameValid(name); name = RegExHelper.GetCleanedFilename(name); return(View()); }
/// <summary> /// Converts an email address to a reasonable file name /// </summary> /// <param name="emailName"></param> /// <returns></returns> public static string EmailToFilename(string emailName) { if (!RegExHelper.IsEmail(emailName)) { throw new Exception("1030-1035: Not an email"); } var emailNameMunged = emailName.ToLower(); emailNameMunged = emailName.Replace("@", "_"); var sbOut = new StringBuilder(); foreach (char c in emailNameMunged) { if (((c >= 'a') && (c <= 'z')) || ((c >= '0') & (c <= '9')) || (c == '_') ) { sbOut.Append(c); } } return(sbOut.ToString()); }
public Dictionary <Units, int> GetMyUnitsInVillage(RequestManager reqManager, int village) { CQ html = GetPlaceHtml(reqManager, village); var units = new Dictionary <Units, int>(); var selector = "form#command-data-form table tbody table.vis td.nowrap a.units-entry-all"; var linkList = html.Select(selector).ToList(); foreach (var item in linkList) { var typeStr = RegExHelper.GetTextWithRegEx(@"units_entry_all_([a-z]+)", item.Id); var type = UnitHelper.GetTypeForString(typeStr); var nrOfUnits = RegExHelper.GetNumberWithRegEx(@"\((\d+)\)", item.InnerText); if (nrOfUnits == 0) { continue; } units.Add(type, nrOfUnits); } return(units); }
private static int GetOrderQueueId(IDomObject item, string building) { var pattern = @"/game\.php\?village=\d+&screen=__building__&action=cancel&id=(\d+)"; var replacedString = pattern.Replace("__building__", building); return(RegExHelper.GetNumberWithRegEx(replacedString, item.OuterHTML)); }
/// <summary> /// Constructor /// </summary> /// <param name="userNode">XML for user</param> /// <param name="userIdFixed">NULL if ID is expected in the XML. If non-NULL we will use the handed in user-id</param> private SiteUser(XmlNode userNode, string userIdFixed, SiteUserAuth?siteUserAuthFixed) { if (userNode.Name.ToLower() != "user") { AppDiagnostics.Assert(false, "Not a user"); throw new Exception("Unexpected content - not user"); } //If we have not been handed a user-id, then it must be in the XML if (string.IsNullOrEmpty(userIdFixed)) { this.Id = userNode.Attributes["id"].Value; } else { this.Id = userIdFixed; } this.Name = userNode.Attributes["name"].Value; this.SiteRole = userNode.Attributes["siteRole"].Value; this.LastLogin = XmlHelper.GetAttributeDateTimeIfExists(userNode, "lastLogin"); this.LastLoginAsText = XmlHelper.GetAttributeIfExists(userNode, "lastLogin", null); //Not all of the REST APIs return full name this.FullName = XmlHelper.GetAttributeIfExists(userNode, "fullName", ""); this.SiteRoleParsed = ParseUserRole(this.SiteRole); AppDiagnostics.Assert(this.SiteRoleParsed != SiteUserRole.Unknown, "Unknown user role: " + this.SiteRole); //If we were not passed in an explicit user authentication, then it needs to be in the XML if (siteUserAuthFixed == null) { this.SiteAuthentication = userNode.Attributes["authSetting"].Value; this.SiteAuthenticationParsed = ParseUserAuthentication(this.SiteAuthentication); AppDiagnostics.Assert(this.SiteAuthenticationParsed != SiteUserAuth.Unknown, "Unknown user auth: " + this.SiteAuthenticationParsed); } else { //Use the explicitly passed in value this.SiteAuthenticationParsed = siteUserAuthFixed.Value; this.SiteAuthentication = UserAuthenticationToString(this.SiteAuthenticationParsed); } this.IsSiteAdmin = ParseIsSiteAdmin(this.SiteRole); //============================================================================= //[2019-10-30] Currently Query User APIs do not return the user's email. //If the User Name is the email (as it is in Tableau Online) then grab that //============================================================================= string candidateEmail = this.Name; if (RegExHelper.IsEmail(candidateEmail)) { this.Email = candidateEmail; } }
/// <summary> /// Adds a standard type mapping based on namespace RegEx replace and filter patterns /// </summary> /// <param name="nsSourceReplaceRegEx">RegEx replace pattern for source namespace</param> /// <param name="nsSourceFilterRegEx">RegEx filter pattern for source namespace</param> /// <param name="nsTargetsRegEx">Array of RegEx replace values for target namespaces</param> /// <param name="viewSuffix">Suffix for type name. Should be "View" or synonym of "View". (Optional)</param> public static void AddTypeMapping(string nsSourceReplaceRegEx, string nsSourceFilterRegEx, string[] nsTargetsRegEx, string viewSuffix = "View") { RegisterViewSuffix(viewSuffix); var replist = new List <string>(); var repsuffix = useNameSuffixesInMappings ? viewSuffix : String.Empty; const string basegrp = "${basename}"; foreach (var t in nsTargetsRegEx) { replist.Add(t + String.Format(nameFormat, basegrp, repsuffix)); } var rxbase = RegExHelper.GetNameCaptureGroup("basename"); var suffix = String.Empty; if (useNameSuffixesInMappings) { suffix = viewModelSuffix; if (!viewModelSuffix.Contains(viewSuffix) && includeViewSuffixInVmNames) { suffix = viewSuffix + suffix; } } var rxsrcfilter = String.IsNullOrEmpty(nsSourceFilterRegEx) ? null : String.Concat(nsSourceFilterRegEx, String.Format(nameFormat, RegExHelper.NameRegEx, suffix), "$"); var rxsuffix = RegExHelper.GetCaptureGroup("suffix", suffix); NameTransformer.AddRule( String.Concat(nsSourceReplaceRegEx, String.Format(nameFormat, rxbase, rxsuffix), "$"), replist.ToArray(), rxsrcfilter ); }
/// <summary> /// Adds a standard type mapping by substituting one subnamespace for another /// </summary> /// <param name="nsSource">Subnamespace of source type</param> /// <param name="nsTargets">Subnamespaces of target type as an array</param> /// <param name="viewSuffix">Suffix for type name. Should be "View" or synonym of "View". (Optional)</param> public static void AddSubNamespaceMapping(string nsSource, string[] nsTargets, string viewSuffix = DefaultViewSuffix) { //need to terminate with "." in order to concatenate with type name later var nsencoded = RegExHelper.NamespaceToRegEx(nsSource + "."); string rxbeforetgt, rxaftersrc, rxaftertgt; string rxbeforesrc = rxbeforetgt = rxaftersrc = rxaftertgt = String.Empty; if (!String.IsNullOrEmpty(nsSource)) { if (!nsSource.StartsWith("*")) { rxbeforesrc = RegExHelper.GetNamespaceCaptureGroup("nsbefore"); rxbeforetgt = @"${nsbefore}"; } if (!nsSource.EndsWith("*")) { rxaftersrc = RegExHelper.GetNamespaceCaptureGroup("nsafter"); rxaftertgt = "${nsafter}"; } } var rxmid = RegExHelper.GetCaptureGroup("subns", nsencoded); var nsreplace = String.Concat(rxbeforesrc, rxmid, rxaftersrc); var nsTargetsRegEx = nsTargets.Select(t => String.Concat(rxbeforetgt, t, ".", rxaftertgt)).ToArray(); AddTypeMapping(nsreplace, null, nsTargetsRegEx, viewSuffix); }
/// <summary> /// Transforms a ViewModel type name into all of its possible View type names. Optionally accepts an instance /// of context object /// </summary> /// <returns>Enumeration of transformed names</returns> /// <remarks>Arguments: /// typeName = The name of the ViewModel type being resolved to its companion View. /// context = An instance of the context or null. /// </remarks> public IList <string> TransformName(string typeName, object context) { Func <string, string> getReplaceString; if (context == null) { getReplaceString = r => r; return(_nameTransformer.Transform(typeName, getReplaceString).ToList()); } var contextstr = _contextSeparator + context; string grpsuffix = String.Empty; if (_useNameSuffixesInMappings) { //Create RegEx for matching any of the synonyms registered var synonymregex = "(" + String.Join("|", _viewSuffixList.ToArray()) + ")"; grpsuffix = RegExHelper.GetCaptureGroup("suffix", synonymregex); } const string grpbase = @"\${basename}"; var patternregex = String.Format(_nameFormat, grpbase, grpsuffix) + "$"; //Strip out any synonym by just using contents of base capture group with context string var replaceregex = "${basename}" + contextstr; //Strip out the synonym getReplaceString = r => Regex.Replace(r, patternregex, replaceregex); //Return only the names for the context return(_nameTransformer.Transform(typeName, getReplaceString).Where(n => n.EndsWith(contextstr)).ToList()); }
public JsonResult SetSchemaName(string name) { if (String.IsNullOrEmpty(name)) { return(Json("A Metadata structure must have a name.", JsonRequestBehavior.AllowGet)); } if (!RegExHelper.IsFilenameValid(name)) { return(Json("Name : \" " + name + " \" is invalid. These special characters are not allowed : \\/:*?\"<>|", JsonRequestBehavior.AllowGet)); } if (SchemaNameExist(name)) { return(Json("A Metadata structure with this name already exist. Please choose a other name.", JsonRequestBehavior.AllowGet)); } TaskManager = (ImportMetadataStructureTaskManager)Session["TaskManager"]; if (TaskManager.Bus.ContainsKey(ImportMetadataStructureTaskManager.SCHEMA_NAME)) { TaskManager.Bus[ImportMetadataStructureTaskManager.SCHEMA_NAME] = name; } else { TaskManager.Bus.Add(ImportMetadataStructureTaskManager.SCHEMA_NAME, name); } return(Json(true, JsonRequestBehavior.AllowGet)); }
public Report GetReport(RequestManager requestManager, int village, int reportItemId) { var html = GetReportHtml(requestManager, village, reportItemId); var topLevelTableRows = html.Select("table.vis tbody tr td.nopad table.vis:nth-child(2) tr").ToList(); var title = HtmlParse.GetElementFromHtmlTable(topLevelTableRows, 0, 1).InnerText.Trim(); var timeReceived = HtmlParse.GetElementFromHtmlTable(topLevelTableRows, 1, 1).InnerText.Trim(); var reportDataEle = HtmlParse.GetElementFromHtmlTable(topLevelTableRows, 2, 0); var luckStr = reportDataEle.Cq()["#attack_luck tbody tr"].Text().Trim(); var luck = RegExHelper.GetdoubleWithRegEx(@"(-?\d+\.\d+)%", luckStr); var report = new Report(); report.Attacker = GetAttackInfo(reportDataEle.Cq(), true); report.Defernder = GetAttackInfo(reportDataEle.Cq(), false); report.Title = title; report.TimeReceived = timeReceived; report.Id = reportItemId; report.AtteckersLuck = luck; return(report); }
/// <summary> /// Adds a standard type mapping based on namespace RegEx replace and filter patterns /// </summary> /// <param name="nsSourceReplaceRegEx">RegEx replace pattern for source namespace</param> /// <param name="nsSourceFilterRegEx">RegEx filter pattern for source namespace</param> /// <param name="nsTargetsRegEx">Array of RegEx replace values for target namespaces</param> /// <param name="viewSuffix">Suffix for type name. Should be "View" or synonym of "View". (Optional)</param> public static void AddTypeMapping(string nsSourceReplaceRegEx, string nsSourceFilterRegEx, string[] nsTargetsRegEx, string viewSuffix = DefaultViewSuffix) { var replist = new List <string>(); Action <string> func; const string basegrp = "${basename}"; var interfacegrp = "${" + InterfaceCaptureGroupName + "}"; if (useNameSuffixesInMappings) { if (viewModelSuffix.Contains(viewSuffix) || !includeViewSuffixInVmNames) { var nameregex = String.Format(nameFormat, basegrp, viewModelSuffix); func = t => { replist.Add(t + "I" + nameregex + interfacegrp); replist.Add(t + "I" + basegrp + interfacegrp); replist.Add(t + nameregex); replist.Add(t + basegrp); }; } else { var nameregex = String.Format(nameFormat, basegrp, "${suffix}" + viewModelSuffix); func = t => { replist.Add(t + "I" + nameregex + interfacegrp); replist.Add(t + nameregex); }; } } else { func = t => { replist.Add(t + "I" + basegrp + interfacegrp); replist.Add(t + basegrp); }; } nsTargetsRegEx.ToList().Apply(t => func(t)); string suffix = useNameSuffixesInMappings ? viewSuffix : String.Empty; var srcfilterregx = String.IsNullOrEmpty(nsSourceFilterRegEx) ? null : String.Concat(nsSourceFilterRegEx, String.Format(nameFormat, RegExHelper.NameRegEx, suffix), "$"); var rxbase = RegExHelper.GetNameCaptureGroup("basename"); var rxsuffix = RegExHelper.GetCaptureGroup("suffix", suffix); //Add a dummy capture group -- place after the "$" so it can never capture anything var rxinterface = RegExHelper.GetCaptureGroup(InterfaceCaptureGroupName, String.Empty); NameTransformer.AddRule( String.Concat(nsSourceReplaceRegEx, String.Format(nameFormat, rxbase, rxsuffix), "$", rxinterface), replist.ToArray(), srcfilterregx ); }
private void btnInfo_MouseEnter(object sender, EventArgs e) { if (!string.IsNullOrEmpty(cboAbilities.Text)) { var description = Lists.Abilities.FirstOrDefault(f => f.Name == cboAbilities.Text).Description; _toolTip.Show(RegExHelper.Wordwrap(description, 100), this.btnInfo, 32767); } }
public void GetNameCaptureGroupShouldUseNameSpaceRegEx() { var groupName = "group"; var result = RegExHelper.GetNamespaceCaptureGroup(groupName); Assert.Equal(@"(?<group>([\p{Lu}\p{Ll}\p{Lt}\p{Lm}\p{Lo}\p{Nl}_][\p{Lu}\p{Ll}\p{Lt}\p{Lm}\p{Lo}\p{Nl}\p{Mn}\p{Mc}\p{Nd}\p{Pc}\p{Cf}_]*\.)*)", result); }
public void GetNameCaptureGroupShouldUseNameSpaceRegEx() { var groupName = "group"; var result = RegExHelper.GetNamespaceCaptureGroup(groupName); Assert.Equal(@"(?<group>([A-Za-z_]\w*\.)*)", result); }
public void ShouldInsertRegexWhenNamespaceHasAsterix() { var ns = "Caliburn.*.WPF.Tests"; var result = RegExHelper.NamespaceToRegEx(ns); Assert.Equal(@"Caliburn\.([\p{Lu}\p{Ll}\p{Lt}\p{Lm}\p{Lo}\p{Nl}_][\p{Lu}\p{Ll}\p{Lt}\p{Lm}\p{Lo}\p{Nl}\p{Mn}\p{Mc}\p{Nd}\p{Pc}\p{Cf}_]*\.)*WPF\.Tests", result); }
public void ShouldEscapeDotsInNamespace() { var ns = "Caliburn.Micro.WPF.Tests"; var result = RegExHelper.NamespaceToRegEx(ns); Assert.Equal(@"Caliburn\.Micro\.WPF\.Tests", result); }
public void ShouldInsertRegexWhenNamespaceHasAsterix() { var ns = "Caliburn.*.WPF.Tests"; var result = RegExHelper.NamespaceToRegEx(ns); Assert.Equal(@"Caliburn\.([A-Za-z_]\w*\.)*WPF\.Tests", result); }
public void GetCaptureGroupReturnsGroupNameAndRegex() { var groupName = "group"; var regex = ".*"; var result = RegExHelper.GetCaptureGroup(groupName, regex); Assert.Equal("(?<group>.*)", result); }
/// <summary> /// /// </summary> /// <remarks></remarks> /// <seealso cref=""/> /// <param name="value"></param> /// <returns></returns> public static string Encode(string value) { string encodedValue = value; // has special characters if (RegExHelper.IsMatch(value, RegExHelper.LUCENE_INVALID_CHARS_REGEX)) { encodedValue = ReplaceSpecialCharacters(value); } return(encodedValue); }
/// <summary> /// Queries for the set of workbooks that the specified user can access /// </summary> /// <param name="signIn"></param> /// <param name="queryForUserId"></param> /// <returns></returns> public static DownloadWorkbooksList CreateAndExecute(TableauServerSignIn signIn, string queryForUserId) { if (!RegExHelper.IsValidIdTableauContentId(queryForUserId)) { throw new Exception("1030-910: User id syntax invalid: " + queryForUserId); } var downloader = new DownloadWorkbooksList(signIn, queryForUserId); downloader.ExecuteRequest(); return(downloader); }
/// <summary> /// Constructor: Call when we want to query the Workbooks on behalf of an explicitly specified user /// </summary> /// <param name="onlineUrls"></param> /// <param name="login"></param> /// <param name="user"></param> public DownloadWorkbooksList(TableauServerSignIn login, string userId, int maxNumberItems = int.MaxValue) : base(login) { //Sanity test if (!RegExHelper.IsValidIdTableauContentId(userId)) { throw new Exception("1030-139: Invalid user ID"); } _onlineUrls = login.ServerUrls; _userIdForWorkbookQuery = userId; _maxNumberItemsReturned = maxNumberItems; _sort = DownloadWorkbooksList.Sort.NoSort; //[2019-10-29] This is currently the only option }
/// <summary> /// Path for storing site thumbnails /// </summary> /// <param name="siteSignIn"></param> /// <returns></returns> public static string LocalFileSystemPath_TempSpace_SiteWorkbookThumbnails(TableauServerSignIn siteSignIn, string workbookId) { if (!RegExHelper.IsValidIdTableauContentId(workbookId)) { throw new Exception("1029-816, invalid workbook id"); } var fullPath = System.IO.Path.Combine( LocalFileSystemPath_TempSpace_Site(siteSignIn), "wb_thumb_" + workbookId); //Create the directory if we need to FileIOHelper.CreatePathIfNeeded(fullPath); return(fullPath); }
private static void AddCustomNamingConventions() { const string groupName = "subname"; string captureGroup = RegExHelper.GetNamespaceCaptureGroup("subname"); string viewPattern = captureGroup + @"View"; const string viewReplacement = @"${" + groupName + "}ViewModel"; ViewModelLocator.NameTransformer.AddRule(viewPattern, viewReplacement); string viewModelPattern = captureGroup + @"ViewModel"; const string viewModelReplacement = @"${" + groupName + "}View"; ViewLocator.NameTransformer.AddRule(viewModelPattern, viewModelReplacement); }
private ReportItem GetReportItemFromTableRow(IDomObject col1, IDomObject col2) { var textEle = col1.Cq().Select("span.quickedit-content"); var text = textEle.FirstElement().InnerText.Trim(); var url = textEle.Select("span.quickedit-content a").FirstElement().GetAttribute("href"); var dateTime = col2.InnerText; var id = RegExHelper.GetNumberWithRegEx( @"/game\.php\?village=\d+&screen=report&mode=attack&group_id=-1&view=(\d+)", url); var reportItem = new ReportItem { Id = id, Title = text, TimeReceived = dateTime }; return(reportItem); }
/// <summary> /// Adds a standard type mapping based on simple namespace mapping /// </summary> /// <param name="nsSource">Namespace of source type</param> /// <param name="nsTargets">Namespaces of target type as an array</param> /// <param name="viewSuffix">Suffix for type name. Should be "View" or synonym of "View". (Optional)</param> public static void AddNamespaceMapping(string nsSource, string[] nsTargets, string viewSuffix = DefaultViewSuffix) { //need to terminate with "." in order to concatenate with type name later var nsencoded = RegExHelper.NamespaceToRegEx(nsSource + "."); //Start pattern search from beginning of string ("^") //unless original string was blank (i.e. special case to indicate "append target to source") if (!String.IsNullOrEmpty(nsSource)) { nsencoded = "^" + nsencoded; } //Capture namespace as "origns" in case we need to use it in the output in the future var nsreplace = RegExHelper.GetCaptureGroup("origns", nsencoded); var nsTargetsRegEx = nsTargets.Select(t => t + ".").ToArray(); AddTypeMapping(nsreplace, null, nsTargetsRegEx, viewSuffix); }
private Dictionary <Units, int> GetUnitsFromReport(List <IDomObject> table, bool lostUnits, bool isAttackTable) { var maxIndex = isAttackTable ? 11 : 12; var row = lostUnits ? 2 : 1; var dict = new Dictionary <Units, int>(); for (var i = 1; i < maxIndex; i++) { var classes = HtmlParse.GetElementFromHtmlTable(table, row, i).ClassName; var typeStr = RegExHelper.GetTextWithRegEx("unit-item-([a-z]+)", classes); var type = UnitHelper.GetTypeForString(typeStr); var nrStr = HtmlParse.GetElementFromHtmlTable(table, row, i).InnerText; var nr = int.Parse(nrStr); dict.Add(type, nr); } return(dict); }
/// <summary> /// Path for storing temp data about a site (e.g. downloaded thumbnails) /// </summary> /// <param name="siteSignIn"></param> /// <returns></returns> public static string LocalFileSystemPath_TempSpace_Site(TableauServerSignIn siteSignIn) { if ((siteSignIn == null) || (string.IsNullOrEmpty(siteSignIn.SiteId))) { throw new Exception("1025-1053: No signed in site info"); } var siteId = siteSignIn.SiteId; if (!RegExHelper.IsValidIdTableauContentId(siteId)) { throw new Exception("1029-815, invalid site id"); } var fullPath = System.IO.Path.Combine(AppSettings.LocalFileSystemPath_TempSpace, @"Sites"); fullPath = System.IO.Path.Combine(fullPath, "site_" + siteId); //Create the directory if we need to FileIOHelper.CreatePathIfNeeded(fullPath); return(fullPath); }
public void GetMatchesTest() { var verbEx = VerbalExpressions .DefaultExpression .StartOfLine() .Then("http") .Maybe("s") .Then("://") .Maybe("www.") .AnythingBut(" ") .EndOfLine(); const string testMe = "https://www.google.com"; var matches = RegExHelper.GetMatches(verbEx, testMe); Assert.AreEqual(1, matches.Count); matches = RegExHelper.GetMatches(verbEx, testMe + " "); Assert.AreEqual(null, matches); }
/// <summary> /// Writes out a chunk of text to a diagnostic file /// </summary> /// <param name="filenameBase">(e.g. 'assert', 'debug'). Must be only A-Z characters</param> /// <param name="writeText"></param> private static void WriteDiagnisticTextToFile(string filenameBase, string writeText) { //SECURITY CHECK: Allow only simple alphabetic filename. //We should NEVER hit this if we are called with normal file names if (!RegExHelper.IsAlphabeticText(filenameBase)) { throw new Exception("67-1258: Unexpected debugging filename: " + filenameBase); } var dateTimeNow = DateTime.UtcNow; string filename = filenameBase + dateTimeNow.Year.ToString() + dateTimeNow.Month.ToString("00") + dateTimeNow.Day.ToString("00") + ".txt"; //Gent the directory var directoryAsserts = AppSettings.LocalFileSystemPath_Diagnostics; FileIOHelper.CreatePathIfNeeded(directoryAsserts); var filenameWithPath = Path.Combine(directoryAsserts, filename); //Write the assert contents into the file File.AppendAllText(filenameWithPath, writeText); }
private static UnitQueueItem GetUnitQueueItem(IDomObject item, string typeStr) { CQ itemCq = item.OuterHTML; var queantAndTypeStr = itemCq.Select("div.unit_sprite.unit_sprite_smaller").ToList().First(); var type = UnitHelper.GetTypeForString(queantAndTypeStr.Classes.ToList().Last()); var domElements = item.ChildElements.ToList(); var quantity = RegExHelper.GetNumberWithRegEx(@"(\d+)", domElements[0].InnerText); var timeUntillCompleeteStr = itemCq.Text(); var timeUntillCompleete = RegExHelper.GetTimeFromString(timeUntillCompleeteStr); var queueItem = new UnitQueueItem { Quantity = quantity, Type = type, TimeLeft = timeUntillCompleete, Id = GetOrderQueueId(item, typeStr) }; return(queueItem); }