Exemple #1
0
 public HttpResponseMessage Delete([FromUri] string token, [FromUri] string id_user)
 {
     try
     {
         if (_authService.CheckAuthorization(token) == true)
         {
             if (_authService.CurrentUser.Id != id_user)
             {
                 return(Request.CreateResponse(HttpStatusCode.Forbidden)); //probojemy usunac innego uzytkownika niz my sami
             }
             else
             {
                 UsersRepo.RemoveUser(id_user);
                 TokenBase.RemoveToken(token); //usunelismy sie = tracimy autentykację
                 return(Request.CreateResponse(HttpStatusCode.OK));
             }
         }
         else
         {
             return(Request.CreateResponse(HttpStatusCode.Unauthorized));
         }
     }
     catch (Exception e)
     {
         WebApiApplication.GlobalLogger.Error(Request + e.ToString());
         var err = new HttpError("Error while removing user");
         return(Request.CreateResponse(HttpStatusCode.InternalServerError, err));
     }
 }
Exemple #2
0
        public void NextTokenShouldNotReturnWhiteSpaceToken()
        {
            TokenBase identifier = TokenCreator.Create <IdentifierToken>("test");
            TokenBase space      = TokenCreator.Create <SpaceToken>();

            StatementBase classStatement  = StatementCreator.CreateClassStatement();
            StatementBase memberStatement = StatementCreator.CreateMemberStatement("test");

            IList <TokenBase> totalList = new List <TokenBase>();

            foreach (TokenBase aToken in classStatement.Tokens)
            {
                totalList.Add(aToken);
            }
            foreach (TokenBase aToken in memberStatement.Tokens)
            {
                totalList.Add(aToken);
            }
            totalList.Add(space);
            totalList.Add(identifier);

            IList <TokenBase> identifierList = new List <TokenBase>();

            identifierList.Add(space);
            identifierList.Add(identifier);

            _manager.Encountered(new[] { classStatement }, classStatement.Tokens.Count(), totalList);
            Assert.AreEqual(identifier, _manager.GetContext(memberStatement.Tokens).NextTokenFromCurrentStatement);
        }
Exemple #3
0
        //When parsing value
        protected void ValidTokenFoundDuringKeyValueParsing(object sender, TokenBase tokenBase)
        {
            switch (tokenBase.Type)
            {
            case TokenType.ValueSeparator:
                ValueParsingComplete();
                break;

            case TokenType.Letter:
                keyTmpValue += tokenBase.Symbol;
                break;

            case TokenType.NewLine:
                ValueParsingComplete();
                KeyParsingComplete();
                InitKeyIdParsing();
                break;

            case TokenType.WhiteSpace:
                if (string.IsNullOrEmpty(keyTmpValue))
                {
                    ValueParsingComplete();
                }
                break;

            case TokenType.ValueMarker:
                InitPureValueParsing();
                break;
            }
        }
Exemple #4
0
        public HttpResponseMessage Post([FromBody] AuthenticationRecord userAuthData)
        {
            try
            {
                if (Authenticate(userAuthData) == true) //user istnieje, haslo sie zgadza
                {
                    var user = _unitOfWork.UsersRepository.GetUserByEmail(userAuthData.Email);

                    if (TokenBase.VerifyUserToken(user) == true) //jesli token juz istnieje  i jest ważny - zwracamy go
                    {
                        var token = TokenBase.GetUserToken(user);
                        return(Request.CreateResponse(HttpStatusCode.OK, token.GetString));
                    }
                    //token nie istnieje - tworzymy go i zwracamy
                    return(Request.CreateResponse(HttpStatusCode.OK, TokenBase.AddNewToken(user).GetString));
                }
                else
                {
                    HttpError err = new HttpError("Authentication Failed!");
                    return(Request.CreateResponse(HttpStatusCode.Unauthorized, err));
                }
            }
            catch (Exception)
            {
                HttpError err = new HttpError("Error while authentication");
                return(Request.CreateResponse(HttpStatusCode.InternalServerError, err));
            }
        }
        public HttpResponseMessage SetDefaultOrganisation(int id)
        {
            var token = TokenBase.ReadToken(HttpContext.Current);

            if (_validation.IsTokenValid(token))
            {
                if (!_validation.VolunteerHasAccessToThisOrg(id, token.Email))
                {
                    return(Messages.ReturnUnauthorized());
                }

                var generateTokenModel = new GenerateTokenModel
                {
                    VolunterId     = token.VolunteerId,
                    Email          = token.Email,
                    OrganisationId = id,
                    Audience       = ConfigurationManager.AppSettings["Audience"],
                    Issuer         = ConfigurationManager.AppSettings["Issuer"],
                    Key            = ConfigurationManager.AppSettings["Key"]
                };

                var jwtSecurityToken = _tokenManager.GenerateToken(generateTokenModel);

                _tokenManager.MakeTokenInvalid(token.TokenId);

                return(Messages.ReturnOk(new
                {
                    token = jwtSecurityToken
                }));
            }

            return(Messages.ReturnUnauthorized());
        }
Exemple #6
0
        public void SignContext(OAuthContext context, TokenBase accessToken)
        {
            EnsureStateIsValid();

            if (accessToken.ConsumerKey != ConsumerKey)
            {
                throw Error.SuppliedTokenWasNotIssuedToThisConsumer(ConsumerKey, accessToken.ConsumerKey);
            }

            var signer = new OAuthContextSigner();
            var auth   = new NonceGenerator();

            context.UseAuthorizationHeader = UseHeaderForOAuthParameters;
            context.ConsumerKey            = accessToken.ConsumerKey;
            context.Token           = accessToken.Token;
            context.TokenSecret     = accessToken.TokenSecret;
            context.SignatureMethod = SignatureMethod;
            context.Timestamp       = DateTime.Now.EpocString();
            context.Nonce           = auth.GenerateNonce();
            context.Version         = "1.0";

            string signatureBase = context.GenerateSignatureBase();

            Console.WriteLine("signature_base: {0}", signatureBase);

            signer.SignContext(context,
                               new SigningContext
            {
                Algorithm = Key, SignatureBase = signatureBase, ConsumerSecret = ConsumerSecret
            });

            Console.WriteLine("oauth_singature: {0}", context.Signature);
        }
Exemple #7
0
        public static async Task <HueUser> FindHueBridge(TokenBase token)
        {
            IBridgeLocator locator = new HttpBridgeLocator();
            var            bridges = await locator.LocateBridgesAsync(TimeSpan.FromSeconds(5));

            var bridge = (from item in bridges
                          where item.BridgeId == token.Id.ToLower()
                          select item).FirstOrDefault();

            if (bridge != null)
            {
                var client = new LocalHueClient(bridge.IpAddress);
                client.Initialize(token.AccessToken);

                var bridgeInfo = await client.GetBridgeAsync();

                var bridgeId = bridgeInfo.Config.BridgeId;

                var user = new HueUser(bridgeInfo);
                user.Token = token;

                return(user);
            }
            else
            {
                throw new InvalidOperationException("The Hue bridge with ID " + token.Id + " not found in current network.");
            }
        }
Exemple #8
0
		public async Task<IResponseResult<IPaginationCollection<T>>> GetAsync(
			TokenBase token, 
			int? skip = null, 
			int? limit = null, 
			bool? withCount = null, 
			string orderBy = null, 
			SortDirection? sortDirection = null,
			string searchKeyword = null)
		{
			if (string.IsNullOrEmpty(searchKeyword) || string.IsNullOrEmpty(searchKeyword.Trim()))
			{
				return await this.ExecuteRequestAsync<PaginationCollection<T>>(
					HttpMethod.Get, 
					$"{this.BaseUrl}/memberships/{this.MembershipId}/{this.Slug}", 
					QueryStringHelper.GetQueryString(skip, limit, withCount, orderBy, sortDirection), 
					HeaderCollection.Add("Authorization", token.ToString()));
			}
			else
			{
				return await this.ExecuteRequestAsync<PaginationCollection<T>>(
					HttpMethod.Get, 
					$"{this.BaseUrl}/memberships/{this.MembershipId}/{this.Slug}/search", 
					QueryStringHelper.GetQueryString(skip, limit, withCount, orderBy, sortDirection).Add("keyword", searchKeyword), 
					HeaderCollection.Add("Authorization", token.ToString()));
			}
		}
Exemple #9
0
        public HttpWebResponse GetResponse(OAuthContext context, TokenBase accessToken)
        {
            SignContext(context, accessToken);

            Uri uri = context.GenerateUri();

            Console.WriteLine("Uri: {0}", uri);

            var request = (HttpWebRequest)WebRequest.Create(uri);

            request.Method = context.RequestMethod;

            if ((context.FormEncodedParameters != null) && (context.FormEncodedParameters.Count > 0))
            {
                request.ContentType = "application/x-www-form-urlencoded";
                using (var writer = new StreamWriter(request.GetRequestStream()))
                {
                    writer.Write(UriUtility.FormatQueryString(context.FormEncodedParameters));
                }
            }

            if (UseHeaderForOAuthParameters)
            {
                request.Headers[Parameters.OAuth_Authorization_Header] = context.GenerateOAuthParametersForHeader();
            }

            return((HttpWebResponse)request.GetResponse());
        }
Exemple #10
0
        public void generate_request_with_raw_body_includes_body_hash()
        {
            var session = new OAuthSession(new OAuthConsumerContext {
                ConsumerKey = "consumer", UseHeaderForOAuthParameters = true
            }, "http://localhost/request", "http://localhost/userauth",
                                           "http://localhost/access");

            var accessToken = new TokenBase {
                ConsumerKey = "consumer", Token = "token", TokenSecret = "secret"
            };

            byte[] rawContents = Encoding.UTF8.GetBytes("Hello World!");

            IConsumerRequest content = session
                                       .EnableOAuthRequestBodyHashes()
                                       .Request(accessToken)
                                       .Post()
                                       .ForUrl("http://localhost/resource")
                                       .WithRawContent(rawContents);

            RequestDescription description = content.GetRequestDescription();

            Assert.Equal(rawContents, description.RawBody);

            Assert.Contains("oauth_body_hash=\"Lve95gjOVATpfV8EL5X4nxwjKHE%3D\"", description.Headers[Parameters.OAuth_Authorization_Header]);
        }
        /// <summary>
        ///		Transforma el token
        /// </summary>
        private TokenSqlBase Transform(TokenBase token)
        {
            switch (token.Type)
            {
            case RuleString:
                return(new TokenSqlString(token));

            case RuleComment:
                return(new TokenSqlComment(token));

            case RuleSql:
                return(new TokenSqlCommand(token));

            case RuleNumber:
                return(new TokenSqlNumber(token));

            case RuleReservedWord:
                return(new TokenSqlReservedWord(token));

            case RuleVariable:
                return(new TokenSqlVariable(token));

            case RuleSeparator:
                return(new TokenSqlSeparator(token));

            default:
                throw new ArgumentException($"Unknown token type: {token.Type}");
            }
        }
Exemple #12
0
        private TokenBase GetNextTokenFromCurrentStatement(int offset)
        {
            int index = _lastIndex + offset;

            if (_tokenList == null || _tokenList.Count() == 0)
            {
                return(null);
            }
            if (index > _tokenList.Count())
            {
                return(null);
            }

            while (index < _tokenList.Count())
            {
                if (!(_tokenList.ElementAt(index) is WhiteSpaceToken))
                {
                    TokenBase token = _tokenList.ElementAt(index);
                    return(token);
                }
                index++;
            }

            return(null);
        }
Exemple #13
0
 private static bool IsValidToken(TokenBase token)
 {
     return
         (token is WhiteSpaceToken ||
          token is OpenAngleBracketToken ||
          token is CloseAngleBracketToken ||
          token is IdentifierToken);
 }
Exemple #14
0
        public OAuthRepository initializeAuth(string consumerKey, string consumerSecret)
        {
            TokenBase token = new TokenBase {
                ConsumerKey = consumerKey
            };

            return(new OAuthRepository(token, consumerSecret));
        }
Exemple #15
0
 /// <summary>
 /// Create a stored token.
 /// </summary>
 /// <param name="tokenBase">The token base instance.</param>
 /// <returns>The token from stored values (create a stored request token).</returns>
 public IToken CreateStoredToken(TokenBase tokenBase)
 {
     if (tokenBase == null)
     {
         throw new ArgumentNullException("tokenBase");
     }
     return(tokenBase);
 }
Exemple #16
0
		public async Task<IResponseResult<T>> GetAsync(string modelId, TokenBase token)
		{
			return await this.ExecuteRequestAsync<T>(
				HttpMethod.Get, 
				$"{this.BaseUrl}/memberships/{this.MembershipId}/{this.Slug}/{modelId}", 
				null, 
				HeaderCollection.Add("Authorization", token.ToString()));
		}
Exemple #17
0
        } // ImplScanString (...)

        //protected virtual TokenBase ImplScanToken ( TextReader textReader )
        //{
        //    if ( textReader == null ) return null;

        //    Char            ch      = ' ';
        //    Int32           chAsc   = -1;
        //    StringBuilder   sb      = new StringBuilder ();
        //    TokenBase       token   = null;

        //    if ( !SkipWhitespaces ( textReader ) ) return null;

        //    while ( (chAsc = textReader.Read ()) != -1 )
        //    {
        //        sb.Append ( ch = (Char) chAsc );

        //        token = LanguageTokens [ sb.ToString () ];

        //        if ( token != null )
        //            if ( token == QuotationMarksToken.Singleton )
        //            {
        //                String strValue = ScanString ( textReader );

        //                if ( strValue == null ) return EofToken.Singleton;

        //                StringToken.Singleton.Value = strValue;

        //                return StringToken.Singleton;
        //            }
        //            else
        //            {
        //                return token;
        //            }

        //        token = LanguageTokens [ ch.ToString () ];

        //        if ( token != null ) return null; // Ritornare un identifier.

        //        if ( ch == '-' || ch >= '0' && ch <= '9' )
        //            ; // is numeric or date
        //        else
        //            ; // is an identifier
        //    }

        //    return EofToken.Singleton;
        //} // End of ImplScanToken (...)

        protected virtual TokenBase ImplScanToken(TextReader textReader)
        {
            if (textReader == null)
            {
                return(null);
            }

            Char          ch    = ' ';
            Int32         chAsc = -1;
            StringBuilder sb    = new StringBuilder();
            TokenBase     token = null;

            if (!SkipWhitespaces(textReader))
            {
                return(null);
            }

            while ((chAsc = textReader.Peek()) != -1)
            {
                if ((token = ImplScanString(textReader)) != null)
                {
                    return(token);
                }
                else if ((token = ImplScanNumericElement(textReader)) != null)
                {
                    return(token);
                }

                sb.Append(ch = (Char)chAsc);

                token = LanguageTokens [sb.ToString()];

                try
                {
                    if (token != null)
                    {
                        return(token);
                    }

                    token = LanguageTokens [ch.ToString()];

                    if (token != null)
                    {
                        return(null);                 // Ritornare un identifier.
                    }
                    if (ch == '-' || ch >= '0' && ch <= '9')
                    {
                        ; // is numeric or date
                    }
                    else
                    {
                        ; // is an identifier
                    }
                } finally { textReader.Read(); }
            }

            return(EofToken.Singleton);
        } // End of ImplScanToken (...)
Exemple #18
0
        public async Task <bool> CheckPermissionAsync(string rbac, TokenBase token)
        {
            var url         = $"{this.AuthApiBaseUrl}/memberships/{this.AuthApiMembershipId}/roles/check-permission";
            var queryString = QueryString.Add("permission", rbac);
            var headers     = HeaderCollection.Add("Authorization", token.ToString());
            var response    = await this.ExecuteRequestAsync(HttpMethod.Get, url, queryString, headers);

            return(response.IsSuccess);
        }
Exemple #19
0
        /// <summary>
        /// Creates a new token at the next position
        /// </summary>
        /// <typeparam name="TTokenType">The token type</typeparam>
        /// <param name="content">The token content</param>
        /// <returns>The requested token</returns>
        public TokenBase Create <TTokenType>(String content) where TTokenType : TokenBase
        {
            object[]  args   = new object[] { _currentLine, _currentColumn, _currentPosition, content };
            TokenBase result = (TTokenType)Activator.CreateInstance(typeof(TTokenType), args);

            UpdateInformation(result);

            return(result);
        }
 public IResponseResult <IPaginationCollection <RevokedToken> > GetRevokedTokens(
     string userId,
     TokenBase token,
     int?skip       = null,
     int?limit      = null,
     bool?withCount = null,
     string orderBy = null,
     SortDirection?sortDirection = null) =>
 this.GetRevokedTokensAsync(userId, token, skip, limit, withCount, orderBy, sortDirection).ConfigureAwait(false).GetAwaiter().GetResult();
Exemple #21
0
        public void RequestTokenWithHmacSha1()
        {
            OAuthConsumer consumer = CreateConsumer(SignatureMethod.HmacSha1);
            OAuthContext  context  = consumer.BuildRequestTokenContext(null);
            TokenBase     token    = provider.GrantRequestToken(context);

            Assert.AreEqual("requestkey", token.Token);
            Assert.AreEqual("requestsecret", token.TokenSecret);
        }
        private void CheckAuthHeader()
        {
            if ((!_sessionAuthorization?.Expired).GetValueOrDefault(false))
            {
                return;
            }

            _sessionAuthorization = _serviceClient.Perform <Dragon6Token>(new DeveloperSessionRequest(_appId, _appSecret));
            Authorization         = $"Bearer {_sessionAuthorization.Token}";
        }
        public void RequestTokenForHmacSha1()
        {
            OAuthConsumer consumer = CreateConsumer(SignatureMethod.HmacSha1);

            TokenBase token = consumer.RequestToken(null);

            Assert.AreEqual("key", token.ConsumerKey);
            Assert.AreEqual("requestkey", token.Token);
            Assert.AreEqual("requestsecret", token.TokenSecret);
        }
Exemple #24
0
        public OsuClientV2(TokenBase token, ClientOptions clientOptions = null)
        {
            clientOptions = clientOptions ?? new ClientOptions();

            _token      = token;
            _httpClient = new HttpClientUtility(clientOptions.Socks5ProxyOptions);
            _httpClient.SetDefaultAuthorization(_token.TokenType, _token.AccessToken);
            User    = new UserEndpoint(token, _httpClient);
            Beatmap = new BeatmapEndpoint(token, _httpClient);
        }
Exemple #25
0
		public IResponseResult<IPaginationCollection<T>> Get(
			TokenBase token, 
			int? skip = null, 
			int? limit = null, 
			bool? withCount = null, 
			string orderBy = null, 
			SortDirection? sortDirection = null,
			string searchKeyword = null) =>
				this.GetAsync(token, skip, limit, withCount, orderBy, sortDirection, searchKeyword)
					.ConfigureAwait(false).GetAwaiter().GetResult();
Exemple #26
0
        private void CheckAuthHeader(DeveloperApiRequest request)
        {
            if ((_sessionAuthorization?.Expired).GetValueOrDefault(true))
            {
                // we don't want this method running if we're getting the token so use the directperform method
                _sessionAuthorization = DirectPerform <DeveloperTokenResponse>(new DeveloperSessionRequest(_appId, _appSecret));
            }

            request.WithAuthHeader($"Bearer {_sessionAuthorization!.Token}");
        }
        public Operand Build(TokenBase token)
        {
            this.Operand = this.CreateOperand(token);

            this.SetRegisterValue(token);
            this.SetNextWordValue(token);
            this.SetLabelValue(token);

            return this.Operand;
        }
Exemple #28
0
        //when parsing a tokenBase id
        protected void ValidTokenFoundDuringKeyIdParsing(object sender, TokenBase tokenBase)
        {
            switch (tokenBase.Type)
            {
            case TokenType.ValueMarker:
                InitPureValueParsing();
                break;

            case TokenType.ValueSeparator:
                SerializeCurrentTmpValueAsAnonymousKey();
                break;

            case TokenType.NewLine:
                if (!string.IsNullOrEmpty(keyTmpValue))
                {
                    SerializeCurrentTmpValueAsAnonymousKey();
                }
                break;

            case TokenType.EQ:
                // multiple EQ tokens in formula
                if (!string.IsNullOrEmpty(currentKey.Id))
                {
                    throw new InvalidTokenException("Equality tokenBase detected, but not expected.");
                }
                KeyIdParsingCompleted();
                InitKeyValueParsing();
                break;

            case TokenType.WhiteSpace:
                //ignore spaces at the begining
                if (!string.IsNullOrEmpty(keyTmpValue))
                {
                    keyTmpValue += tokenBase.Symbol;
                }
                break;

            case TokenType.Letter:
                keyTmpValue += tokenBase.Symbol;
                break;

            case TokenType.CategoryOpening:
                KeyParsingComplete();
                CategoryParsingComplete();
                InitCategoryParsing();
                break;

            case TokenType.InlineComment:
                InitCommentParsing(InitKeyIdParsing);
                break;

            default:
                throw new InvalidTokenException("Invalid tokenBase found during parsing of the file: " + tokenBase.Symbol);
            }
        }
Exemple #29
0
        protected void InvalidTokenFound(object sender, TokenBase tokenBase)
        {
            var builder = new StringBuilder();

            builder.AppendLine($"Invalid tokenBase found during {parsingType} parsing: ");
            builder.AppendLine($"Symbol: {tokenBase.Symbol}");
            builder.AppendLine($"Token type: {tokenBase.Type}");
            builder.AppendLine($"Allowed tokens: {string.Join(", ", parser.AllowedTokens.Select(t => t.Type.ToString()))}");
            builder.AppendLine($"Ignored tokens: {string.Join(", ", parser.IgnoredTokens.Select(t => t.Type.ToString()))}");
            throw new InvalidTokenException(builder.ToString());
        }
Exemple #30
0
        /// <summary>
        /// Parse additional tokens from the source to fill in empty spaces in the provided
        /// previously parsed list
        /// </summary>
        /// <param name="source">The source</param>
        /// <param name="previouslyParsed">The previously parsed</param>
        /// <returns>A full list of tokens</returns>
        public IEnumerable <TokenBase> Parse(String source, IEnumerable <TokenBase> previouslyParsed)
        {
            IList <TokenBase> completeTokenList = new List <TokenBase>();

            if (previouslyParsed.Count() > 0)
            {
                completeTokenList.Add(previouslyParsed.ElementAt(0));
            }

            for (int i = 1; i < previouslyParsed.Count(); i++)
            {
                TokenBase previousToken = previouslyParsed.ElementAt(i - 1);
                TokenBase currentToken  = previouslyParsed.ElementAt(i);

                int previousTokendEndPosition = previousToken.Position + previousToken.Content.Length;
                int currentTokenStartPosition = currentToken.Position;
                //the current token has to start at least at the previous token + 1
                if (currentTokenStartPosition >= previousTokendEndPosition + 1)
                {
                    int    amountOfTokens = currentTokenStartPosition - previousTokendEndPosition;
                    String whitespace     = source.Substring(previousTokendEndPosition, amountOfTokens);

                    //get indices
                    int whitespaceLine   = previousToken.Line;
                    int whitespaceColumn = previousToken.Column + previousToken.Content.Length;
                    int currentPosition  = previousTokendEndPosition;

                    //parse char for char
                    foreach (Char aChar in whitespace.ToCharArray())
                    {
                        if (aChar.Equals('\n'))
                        {
                            completeTokenList.Add(new NewLineToken(whitespaceLine, whitespaceColumn, currentPosition));
                            //reset line and column counts
                            whitespaceLine++;
                            whitespaceColumn = 0;
                        }
                        else if (aChar.Equals(' '))
                        {
                            completeTokenList.Add(new SpaceToken(whitespaceLine, whitespaceColumn, currentPosition));
                        }
                        else if (aChar.Equals('\t'))
                        {
                            completeTokenList.Add(new TabToken(whitespaceLine, whitespaceColumn, currentPosition));
                        }
                        //increment column and position
                        whitespaceColumn++;
                        currentPosition++;
                    }
                }
                completeTokenList.Add(currentToken);
            }
            return(completeTokenList);
        }
 protected override void SetNextWordValue(TokenBase token)
 {
     if (this.leftToken is HexToken)
     {
         this.Operand.NextWord = Convert.ToInt32(this.leftToken.Content, 16);
     }
     else if (this.leftToken is LabelReferenceToken)
     {
         this.Operand.Label = this.leftToken.Content;
     }
 }
Exemple #32
0
        internal static bool TryGetValueToken(ref string text, out TokenBase token, bool requireReturnValue = true)
        {
            string temp = null;

            token = null;
            foreach (TokenBase type in valueTypeInstanceList)
            {
                temp = text;
                if (type.TryGetToken(ref temp, out token, requireReturnValue))
                {
                    break;
                }
                token = null;
            }
            if (token == null)
            {
                return(false);
            }
            text = temp;

            if (token.ReturnType != typeof(void))
            {
                while (true)
                {
                    temp = temp.TrimStart();
                    bool      cont = false;
                    TokenBase newToken;
                    foreach (TokenBase type in postValueTypeInstanceList)
                    {
                        if (type.TryGetToken(ref temp, out newToken, requireReturnValue))
                        {
                            if (newToken.SetPostTarget(token))
                            {
                                token = newToken;
                                text  = temp;
                                cont  = true;
                                break;
                            }
                        }
                    }
                    if (!cont)
                    {
                        break;
                    }
                }

                if (token is IPostToken)
                {
                    token = new PostTokenChainToken(token);
                }
            }

            return(true);
        }
 protected override void SetNextWordValue(TokenBase token)
 {
     if (token is HexToken)
     {
         this.Operand.NextWord = Convert.ToInt32(token.Content, 16);
     }
     else if (token is DecimalToken)
     {
         this.Operand.NextWord = Convert.ToInt32(token.Content, 10);
     }
 }
 public bool IsTokenToBeIgnored(TokenBase token)
 {
     return false;
 }
 public string ConsumeToken(string line, TokenBase token)
 {
     return line.Substring(token.Content.Length);
 }
 protected virtual void SetNextWordValue(TokenBase token)
 {
 }
 protected virtual void SetLabelValue(TokenBase token)
 {
 }
 protected override Operand CreateOperand(TokenBase token)
 {
     return new IndirectNextWordOffsetOperand();
 }
 protected override Operand CreateOperand(TokenBase token)
 {
     return new NextWordOperand();
 }
 protected abstract Operand CreateOperand(TokenBase token);
 public bool IsTokenToBeIgnored(TokenBase token)
 {
     return token is WhiteSpaceToken;
 }
 public Operand CreateOperand(TokenBase token)
 {
     return OperandCreationStrategyMapper[token.GetType()](token); 
 }
 public virtual bool IsTokenToBeIgnored(TokenBase token)
 {
     return this.IgnoreTokenStrategy.IsTokenToBeIgnored(token);
 }
        protected override Operand CreateOperand(TokenBase token)
        {
            var registerType = token.Content.ToUpper();

            return RegisterCreationStrategyMapper.ContainsKey(registerType) ? RegisterCreationStrategyMapper[registerType]() : new RegisterOperand();
        }
Exemple #45
0
 private void ConsumeToken(TokenBase matcher)
 {
     this.LineRemaining = this.ConsumeTokenStrategy.ConsumeToken(this.LineRemaining, matcher);
     this.Position += this.LineRemaining.StartsWith(matcher.Content) ? 0 : matcher.Content.Length;
 }
 protected override void SetLabelValue(TokenBase token)
 {
     this.Operand.Label = token.Content;
 }
 protected virtual void SetRegisterValue(TokenBase token)
 {
 }
 public bool IsTokenToBeConsumed(TokenBase token)
 {
     return this.IsTokenToBeIgnored(token);
 }
 public IndirectNextWordOffsetOperandBuilder(TokenBase leftToken)
 {
     this.leftToken = leftToken;
 }
 public string ConsumeToken(string line, TokenBase token)
 {
     return this.IsTokenToBeConsumed(token) ? line.Substring(token.Content.Length) : line;
 }
 protected override void SetNextWordValue(TokenBase token)
 {
     this.Operand.NextWord = 0;
 }
 protected override void SetRegisterValue(TokenBase token)
 {
     this.Operand.RegisterValue = 
         RegisterOperand.ConvertTokenContentToRegisterIdentifier(token.Content);
 }
 protected override Operand CreateOperand(TokenBase token)
 {
     return new IndirectRegisterOperand();
 }
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="ExpectedTokenTypeToSet">The type of token we are expecting</param>
 /// <param name="TokenFoundToSet">The type of token we found</param>
 public ExpectingTokenException(Type ExpectedTokenTypeToSet, TokenBase TokenFoundToSet)
 {
     ExpectedTokenType = ExpectedTokenTypeToSet;
     TokenFound = TokenFoundToSet;
 }