public async Task <IViewComponentResult> InvokeAsync() { // ModelBinder is not supported in view components so we have to bind // this manually. We have an issue open to try and improve the experience here // https://github.com/cofoundry-cms/cofoundry/issues/125 var webQuery = new SearchBlogPostsQuery(); webQuery.PageNumber = IntParser.ParseOrDefault(Request.Query[nameof(webQuery.PageNumber)]); webQuery.PageSize = IntParser.ParseOrDefault(Request.Query[nameof(webQuery.PageSize)]); webQuery.CategoryId = IntParser.ParseOrDefault(Request.Query[nameof(webQuery.CategoryId)]); var query = new SearchCustomEntityRenderSummariesQuery(); query.CustomEntityDefinitionCode = BlogPostCustomEntityDefinition.DefinitionCode; query.PageNumber = webQuery.PageNumber; query.PageSize = 30; query.PublishStatus = PublishStatusQuery.Published; // TODO: Filtering by Category (webQuery.CategoryId) // Searching/filtering custom entities is not implemented yet, but it // is possible to build your own search index using the message handling // framework or writing a custom query against the UnstructuredDataDependency table // See issue https://github.com/cofoundry-cms/cofoundry/issues/12 var entities = await _customEntityRepository.SearchCustomEntityRenderSummariesAsync(query); var viewModel = await MapBlogPostsAsync(entities); return(View(viewModel)); }
public void TryParseInt_GivenStringNumber_ParseToIntNumber(string value, int expected) { int actual; var succseful = IntParser.TryParseInt(value, out actual); Assert.Equal(expected, actual); }
static int Second(string inputFile) { var parser = new IntParser(); var inputs = parser.ReadData(inputFile).ToList(); return(StartCallingNumbers(inputs, 30000000)); }
public void AfterLoop(IntParser parser) { if (parser.AllowHexSpecifier) { number = (Int64)hex; } }
/// <summary> /// Indicates whether the specified url matches this routing rule. /// </summary> /// <param name="url">The url to test</param> /// <param name="pageRoute">The page route already matched to this url.</param> public bool MatchesRule(string url, PageRoute pageRoute) { if (url == null) { throw new ArgumentNullException(nameof(url)); } if (string.IsNullOrWhiteSpace(url)) { throw new ArgumentEmptyException(nameof(url)); } if (pageRoute == null) { throw new ArgumentNullException(nameof(pageRoute)); } var routingPart = GetRoutingPart(url, pageRoute); if (string.IsNullOrEmpty(routingPart)) { return(false); } var match = Regex.Match(routingPart, ROUTE_REGEX); if (!match.Success) { return(false); } var isMatch = IntParser.ParseOrDefault(match.Groups[1].Value) > 0; return(isMatch); }
/// <summary> /// Returns a query that can be used to look up the CustomEntityRoute relating /// to the matched entity. Throws an exception if the MatchesRule returns false, so /// check this before calling this method. /// </summary> /// <param name="url">The url to parse custom entity key data from</param> /// <param name="pageRoute">The page route matched to the url</param> /// <returns>An IQuery object that can used to query for the CustomEntityRoute</returns> public IQuery <CustomEntityRoute> ExtractRoutingQuery(string url, PageRoute pageRoute) { if (url == null) { throw new ArgumentNullException(nameof(url)); } if (string.IsNullOrWhiteSpace(url)) { throw new ArgumentEmptyException(nameof(url)); } if (pageRoute == null) { throw new ArgumentNullException(nameof(pageRoute)); } if (!MatchesRule(url, pageRoute)) { throw new ArgumentException(nameof(url) + $" does not match the specified page route. {nameof(ExtractRoutingQuery)} can only be called after a successful page route match.", nameof(url)); } var routingPart = GetRoutingPart(url, pageRoute); var customEntityId = IntParser.ParseOrDefault(routingPart); var query = new GetCustomEntityRouteByPathQuery(); query.CustomEntityDefinitionCode = pageRoute.CustomEntityDefinitionCode; query.CustomEntityId = customEntityId; if (pageRoute.Locale != null) { query.LocaleId = pageRoute.Locale.LocaleId; } return(query); }
public static DateTime?GuessBirthDate(string number, DateTime?overrideNow = null) { if (IsFnr(number) == false && IsDNumber(number) == false) { return(null); } var d = IntParser.ParseOrNull(number.Substring(0, 2)); var m = IntParser.ParseOrNull(number.Substring(2, 2)); var y = IntParser.ParseOrNull(number.Substring(4, 2)); if (IsDNumber(number)) { d -= 40; } var birthDate = DateTimeParser.ParseOrNull(d.ToString().PadLeft(2, '0') + m.ToString().PadLeft(2, '0') + "19" + y.ToString().PadLeft(2, '0'), "ddMMyyyy"); if (birthDate.HasValue == false) { return(null); } const int maxYearsGuess = 100; var today = overrideNow ?? DateTime.Today; if (today.Year - birthDate.Value.Year >= maxYearsGuess) { birthDate = birthDate.Value.AddYears(maxYearsGuess); } return(birthDate); }
static void Main(string[] args) { IntParser parser = new IntParser(); string s = "104"; Console.WriteLine(s + " - " + parser.Parse(s) + "\n"); s = "1"; Console.WriteLine(s + " - " + parser.Parse(s) + "\n"); s = "0"; Console.WriteLine(s + " - " + parser.Parse(s) + "\n"); s = "14"; Console.WriteLine(s + " - " + parser.Parse(s) + "\n"); s = "1MSD0"; Console.WriteLine(s + " - " + parser.Parse(s) + "\n"); s = "154645"; Console.WriteLine(s + " - " + parser.Parse(s) + "\n"); s = "1546451127168460"; Console.WriteLine(s + " - " + parser.Parse(s) + "\n"); s = ""; Console.WriteLine(s + " - " + parser.Parse(s) + "\n"); Console.ReadLine(); }
static FieldCacheImpl() { BYTE_PARSER = new AnonymousClassByteParser(); SHORT_PARSER = new AnonymousClassShortParser(); INT_PARSER = new AnonymousClassIntParser(); FLOAT_PARSER = new AnonymousClassFloatParser(); }
/// <summary> /// Gets the UserId of the currently logged in user for a specific UserArea, /// regardless of the ambient authentication scheme. Useful in multi-userarea /// scenarios where you need to ignore the ambient user and check for permissions /// against a specific user area. /// </summary> /// <param name="userAreaCode">The unique identifying code fo the user area to check for.</param> public async Task <int?> GetUserIdByUserAreaCodeAsync(string userAreaCode) { if (userAreaCode == null) { throw new ArgumentNullException(nameof(userAreaCode)); } if (cachedUserIdArea == userAreaCode && userIdCache.HasValue) { return(userIdCache.Value); } var scheme = CofoundryAuthenticationConstants.FormatAuthenticationScheme(userAreaCode); var result = await _httpContextAccessor.HttpContext.AuthenticateAsync(scheme); if (!result.Succeeded) { return(null); } var userIdClaim = result.Principal.FindFirst(ClaimTypes.NameIdentifier); if (userIdClaim == null) { return(null); } var userId = IntParser.ParseOrNull(userIdClaim.Value); return(userId); }
public int?GetCurrentUserId() { var cachedUserId = _inMemoryUserSessionService.GetCurrentUserId(); if (cachedUserId.HasValue) { return(cachedUserId); } var user = _httpContextAccessor?.HttpContext?.User; var userIdClaim = user?.FindFirst(CofoundryClaimTypes.UserId); var userAreaClaim = user?.FindFirst(CofoundryClaimTypes.UserAreaCode); if (userIdClaim == null || userAreaClaim == null) { return(null); } // User has been signed out during this request so ignore if (_signedOutUserAreas.Contains(userAreaClaim.Value)) { return(null); } // Otherwise get it from the Identity var userId = IntParser.ParseOrNull(userIdClaim.Value); return(userId); }
/// <summary> /// Verifies the security stamp claim in the specified <paramref name="principal"/>. If the validation /// if successful then a <see cref="IClaimsPrincipalBuilderContext"/> instance is returned which can be /// used to refresh the principal. If the stamp is invalid for any reason then <see langword="null"/> /// is returned. /// </summary> /// <param name="principal">The principal to verify.</param> protected virtual async Task <IClaimsPrincipalBuilderContext> VerifyClaimsPrincipalAsync(ClaimsPrincipal principal) { if (principal == null) { return(null); } var userId = IntParser.ParseOrDefault(principal.FindFirstValue(CofoundryClaimTypes.UserId)); var context = await _claimsPrincipalBuilderContextRepository.GetAsync(userId); if (context == null) { return(null); } var securityStampClaim = principal.FindFirstValue(CofoundryClaimTypes.SecurityStamp); if (string.IsNullOrEmpty(context.SecurityStamp) || securityStampClaim == context.SecurityStamp) { return(context); } _logger.LogDebug("Security stamp validation failed."); return(null); }
public void TryParseInt_GivenIncorrectStringNumber_ShouldFalse(string value, bool expected) { int number; var actual = IntParser.TryParseInt(value, out number); Assert.Equal(expected, actual); }
public KeywordParser() { Keywords = new HashSet <string>() { "PRINT", "LENGTH", "READ", "WRITE", "int", "int[]", "if", "endif", "new", "while", "endwhile" }; PrintParser = Parse.String("PRINT").Text().Token(); LengthParser = Parse.String("LENGTH").Text().Token(); ReadParser = Parse.String("READ").Text().Token(); WriteParser = Parse.String("WRITE").Text().Token(); IntParser = Parse.String("int").Text().Token(); IntArrayParser = Parse.String("int[]").Text().Token(); NewParser = Parse.String("new").Text().Token(); IfParser = Parse.String("if").Text().Token(); EndIfParser = Parse.String("endif").Text().Token(); WhileParser = Parse.String("while").Text().Token(); EndWhileParser = Parse.String("endwhile").Text().Token(); NotKeywordParser = Parse.Not( IntParser .Or(IfParser) .Or(EndIfParser) .Or(WhileParser) .Or(EndWhileParser) .Or(NewParser) .Or(PrintParser) .Or(LengthParser) .Or(ReadParser) .Or(WriteParser) ); }
protected internal override object CreateValue(IndexReader reader, object entryKey) { Entry entry = (Entry)entryKey; System.String field = entry.field; IntParser parser = (IntParser)entry.custom; int[] retArray = new int[reader.MaxDoc()]; TermDocs termDocs = reader.TermDocs(); TermEnum termEnum = reader.Terms(new Term(field)); try { do { Term term = termEnum.Term(); if (term == null || (object)term.Field() != (object)field) { break; } int termval = parser.ParseInt(term.Text()); termDocs.Seek(termEnum); while (termDocs.Next()) { retArray[termDocs.Doc()] = termval; } }while (termEnum.Next()); } finally { termDocs.Close(); termEnum.Close(); } return(retArray); }
/// <summary> /// Indicates whether the specified url matches this routing rule. /// </summary> /// <param name="url">The url to test</param> /// <param name="pageRoute">The page route already matched to this url.</param> public bool MatchesRule(string url, PageRoute pageRoute) { if (url == null) { throw new ArgumentNullException(nameof(url)); } if (string.IsNullOrWhiteSpace(url)) { throw new ArgumentEmptyException(nameof(url)); } if (pageRoute == null) { throw new ArgumentNullException(nameof(pageRoute)); } var routingPart = GetRoutingPart(url, pageRoute); if (string.IsNullOrEmpty(routingPart)) { return(false); } var isMatch = IntParser.ParseOrDefault(routingPart) > 0; return(isMatch); }
private AddUserCommand MapCommand(AddUserWithTemporaryPasswordCommand command) { // The password policy should be configured with the definitive min-length // as an attribute, but otherwise fall-back to the configured option var passwordPolicy = _passwordPolicyService.GetDescription(command.UserAreaCode); var minLengthAttribute = passwordPolicy.Attributes.GetOrDefault(PasswordPolicyAttributes.MinLength); var options = _userAreaDefinitionRepository.GetOptionsByCode(command.UserAreaCode); var minLength = IntParser.ParseOrDefault(minLengthAttribute, options.Password.MinLength); var newUserCommand = new AddUserCommand() { FirstName = command.FirstName, LastName = command.LastName, DisplayName = command.DisplayName, Email = command.Email, Username = command.Username, Password = _passwordGenerationService.Generate(minLength), RequirePasswordChange = true, UserAreaCode = command.UserAreaCode, RoleId = command.RoleId, RoleCode = command.RoleCode }; return(newUserCommand); }
public static Either <TLeft, int> ParseToInt <TLeft>( this Either <TLeft, string> source, NumberStyles style, TLeft left) { return(source.FlatMap(x => IntParser.Parse <TLeft>(x, style, left))); }
public static Either <TLeft, int> ParseToInt <TLeft>( this Either <TLeft, string> source, IFormatProvider provider, TLeft left) { return(source.FlatMap(x => IntParser.Parse <TLeft>(x, provider, left))); }
protected internal override System.Object CreateValue(IndexReader reader, Entry entryKey) { Entry entry = (Entry)entryKey; System.String field = entry.field; IntParser parser = (IntParser)entry.custom; if (parser == null) { try { return(wrapper.GetInts(reader, field, Lucene.Net.Search.FieldCache_Fields.DEFAULT_INT_PARSER)); } catch (System.FormatException ne) { return(wrapper.GetInts(reader, field, Lucene.Net.Search.FieldCache_Fields.NUMERIC_UTILS_INT_PARSER)); } } int[] retArray = null; TermDocs termDocs = reader.TermDocs(); TermEnum termEnum = reader.Terms(new Term(field)); try { do { Term term = termEnum.Term(); if (term == null || (System.Object)term.Field() != (System.Object)field) { break; } int termval = parser.ParseInt(term.Text()); if (retArray == null) { // late init retArray = new int[reader.MaxDoc()]; } termDocs.Seek(termEnum); while (termDocs.Next()) { retArray[termDocs.Doc()] = termval; } }while (termEnum.Next()); } catch (StopFillCacheException stop) { } finally { termDocs.Close(); termEnum.Close(); } if (retArray == null) { // no values retArray = new int[reader.MaxDoc()]; } return(retArray); }
public static Either <TLeft, int> ParseToInt <TLeft>( this string source, NumberStyles style, IFormatProvider provider, TLeft left) { return(IntParser.Parse <TLeft>(source, style, provider, left)); }
public void Read(Domain.Member member, CheckStylesItem item) { var linesOfCode = IntParser.Match(item.Message).Value.AsInt(); member.StartLine = item.Line; member.EndLine = member.StartLine + linesOfCode + PuppyCrawlMethodFudgeFactor; member.LinesOfCode = linesOfCode; }
private async Task <int?> GetCurrentlySignedInUserId(HttpClient client) { var response = await client.GetAsync("/tests/users/current"); response.EnsureSuccessStatusCode(); var result = await response.Content.ReadAsStringAsync(); return(IntParser.ParseOrNull(result)); }
/// <summary> /// ModelBinder is not supported in view components so we have to bind /// this manually. We have an issue open to try and improve the experience here /// https://github.com/cofoundry-cms/cofoundry/issues/125 /// </summary> private SearchBlogPostsQuery ModelBind() { var webQuery = new SearchBlogPostsQuery(); webQuery.PageNumber = IntParser.ParseOrDefault(Request.Query[nameof(webQuery.PageNumber)]); webQuery.PageSize = IntParser.ParseOrDefault(Request.Query[nameof(webQuery.PageSize)]); webQuery.CategoryId = IntParser.ParseOrDefault(Request.Query[nameof(webQuery.CategoryId)]); return(webQuery); }
public void ParseInt_GivenNull_ArgumentNullException() { //Arrange string inputString = null; // Act Action actual = () => IntParser.ParseInt(inputString); // Assert Assert.Throws <ArgumentNullException>(actual); }
public void ParseInt_GivenIncorrectStringNumber_ShouldIntFormatException() { //Arrange var inputString = "12Fr444"; // Act Action actual = () => IntParser.ParseInt(inputString); // Assert Assert.Throws <IntFormatException>(actual); }
public void ParseInt_GivenStringNumberToLargeInt_ShouldIntSizeException(string number) { //Arrange var inputString = number; // Act Action actual = () => IntParser.ParseInt(inputString); // Assert Assert.Throws <IntSizeException>(actual); }
/// <summary> /// Parses the specified literal. Throws exceptions when angry /// </summary> /// <param name="literal">The literal.</param> /// <returns></returns> /// <exception cref="FormatException"></exception> private int ParseInt(string literal) { var v = IntParser.TryParse(literal); if (!v.HasValue) { throw new FormatException(); } return(v.Value); }
/// <summary> /// Creates DbUpateCommands from sql scripts embedded in an assembly. Only new schema updates /// are included and functions/sps/triggers etc are only returned if there are any relevant schema /// updates, so you need to create a schema update file if you want to force these to update. /// </summary> /// <param name="assembly">The assembly to scan for sql scripts.</param> /// <param name="currentVersion">The current version of the module</param> /// <param name="scriptPath">The folder path of the script files which defaults to 'Install.Db.' (which equates to 'Install/Db/')</param> /// <returns>Collecton of IUpdateCommands that represents all the required db updates</returns> public IEnumerable <IVersionedUpdateCommand> Create(Assembly assembly, ModuleVersion currentVersion, string scriptPath = "Install.Db.") { Condition.Requires(assembly).IsNotNull(); var scriptFiles = GetScripts(assembly, scriptPath); var commands = new List <UpdateDbCommand>(); int maxVersionNumber = 0; // Get schema scripts we need so we know the version number. foreach (var scriptFile in scriptFiles.Where(s => s.Contains(".Schema."))) { var fileName = GetScriptFileName(scriptFile); var version = IntParser.ParseOrNull(fileName); if (!version.HasValue) { throw new InvalidCastException("Unable to parse version number from schema update file: " + scriptFile); } if (currentVersion != null && version.Value <= currentVersion.Version) { continue; } var command = new UpdateDbCommand(); command.Version = version.Value; command.ScriptType = DbScriptType.Schema; command.Sql = GetResource(assembly, scriptFile); command.Description = scriptFile; command.FileName = fileName; commands.Add(command); if (maxVersionNumber < version.Value) { maxVersionNumber = version.Value; } } if (!commands.Any()) { return(Enumerable.Empty <IVersionedUpdateCommand>()); } foreach (var scriptFile in scriptFiles.Where(s => !s.Contains(".Schema."))) { var command = new UpdateDbCommand(); command.Version = maxVersionNumber; command.Sql = GetResource(assembly, scriptFile); command.ScriptType = MapScriptType(scriptFile); command.Description = scriptFile; command.FileName = GetScriptFileName(scriptFile); commands.Add(command); } return(commands); }
public void ParseExtremesTests(string input) { try { IntParser.Parse(input); } catch (Exception exception) { exception.GetType().Should().Be <ArgumentException>(); } }
// inherit javadocs public virtual int[] GetInts(IndexReader reader, System.String field, IntParser parser) { return (int[]) caches[typeof(int)].Get(reader, new Entry(field, parser)); }
private int bottom; // Value of bottom of queue internal IntComparator(int numHits, System.String field, Lucene.Net.Search.Parser parser) { values = new int[numHits]; this.field = field; this.parser = (IntParser) parser; }
// inherit javadocs public virtual int[] GetInts(IndexReader reader, System.String field, IntParser parser) { field = String.Intern(field); System.Object ret = Lookup(reader, field, parser); if (ret == null) { int[] retArray = new int[reader.MaxDoc()]; if (retArray.Length > 0) { TermDocs termDocs = reader.TermDocs(); TermEnum termEnum = reader.Terms(new Term(field, "")); try { if (termEnum.Term() == null) { throw new System.SystemException("no terms in field " + field); } do { Term term = termEnum.Term(); if (term.Field() != field) break; int termval = parser.ParseInt(term.Text()); termDocs.Seek(termEnum); while (termDocs.Next()) { retArray[termDocs.Doc()] = termval; } } while (termEnum.Next()); } finally { termDocs.Close(); termEnum.Close(); } } Store(reader, field, parser, retArray); return retArray; } return (int[]) ret; }
static FieldCacheImpl() { INT_PARSER = new AnonymousClassIntParser(); FLOAT_PARSER = new AnonymousClassFloatParser(); }
// inherit javadocs public virtual int[] GetInts(IndexReader reader, System.String field, IntParser parser) { return (int[]) ((Cache) caches[System.Type.GetType("System.Int32")]).Get(reader, new Entry(field, parser)); }
static FieldCache_Fields() { DEFAULT = new FieldCacheImpl(); DEFAULT_BYTE_PARSER = new AnonymousClassByteParser(); DEFAULT_SHORT_PARSER = new AnonymousClassShortParser(); DEFAULT_INT_PARSER = new AnonymousClassIntParser(); DEFAULT_FLOAT_PARSER = new AnonymousClassFloatParser(); DEFAULT_LONG_PARSER = new AnonymousClassLongParser(); DEFAULT_DOUBLE_PARSER = new AnonymousClassDoubleParser(); NUMERIC_UTILS_INT_PARSER = new AnonymousClassIntParser1(); NUMERIC_UTILS_FLOAT_PARSER = new AnonymousClassFloatParser1(); NUMERIC_UTILS_LONG_PARSER = new AnonymousClassLongParser1(); NUMERIC_UTILS_DOUBLE_PARSER = new AnonymousClassDoubleParser1(); }