Ejemplo n.º 1
0
        private DataView ConsultarDataViewDaConsultaAtual(out int top)
        {
            var view      = ConsultarTabelaComDadosVirtuais().DefaultView;
            var sql       = CommandText.ToLower();
            var indiceTop = sql.IndexOf("select top ", StringComparison.Ordinal);
            var fimTop    = sql.IndexOf(" ", 11, StringComparison.Ordinal);

            top = ((indiceTop == 0) && (fimTop > 0))
                                ? Convert.ToInt32(sql.Substring(11, fimTop - 11))
                                : 0;
            var indiceWhere = sql.IndexOf("where", StringComparison.Ordinal);
            var condicao    = (indiceWhere > 0)
                                ? ConsultarCondicaoParaFiltragem(CommandText.Substring(indiceWhere + 5))
                                : string.Empty;
            var indiceOrderby = sql.IndexOf("order by", StringComparison.Ordinal);

            if ((indiceOrderby > 0) && (indiceOrderby > indiceWhere))
            {
                if (indiceWhere > 0)
                {
                    condicao = condicao.Substring(0, indiceOrderby - indiceWhere - 8 + 1 - 5 + 1);
                }
                view.Sort = CommandText.Substring(indiceOrderby + 8);
            }
            view.RowFilter = condicao;
            return(view);
        }
Ejemplo n.º 2
0
        public IDataReader ExecuteReader()
        {
            var view      = ConsultarTabelaComDadosVirtuais().DefaultView;
            var sql       = CommandText.ToLower();
            var indiceTop = sql.IndexOf("select top ", StringComparison.Ordinal);
            var fimTop    = sql.IndexOf(" ", 11, StringComparison.Ordinal);
            var top       = ((indiceTop == 0) && (fimTop > 0))
                ? Convert.ToInt32(sql.Substring(11, fimTop - 11))
                : 0;
            var indiceWhere = sql.IndexOf("where", StringComparison.Ordinal);
            var condicao    = (indiceWhere > 0)
                                ? ConsultarCondicaoParaFiltragem(CommandText.Substring(indiceWhere + 5))
                                : string.Empty;
            var indiceOrderby = sql.IndexOf("order by", StringComparison.Ordinal);

            if ((indiceOrderby > 0) && (indiceOrderby > indiceWhere))
            {
                condicao  = condicao.Substring(0, indiceOrderby - indiceWhere - 8 + 1 - 5 + 1);
                view.Sort = CommandText.Substring(indiceOrderby + 8);
            }
            if (!string.IsNullOrEmpty(condicao))
            {
                view.RowFilter = condicao;
            }
            return(new DataReaderFake(view, top));
        }
Ejemplo n.º 3
0
        protected override DbDataReader ExecuteDbDataReader(CommandBehavior behavior)
        {
            if (ReaderMethodCache.TryGetValue(CommandText, out var cached) == false)
            {
                var lastDotIndex = CommandText.LastIndexOf('.');

                var typeString = CommandText.Substring(0, lastDotIndex);
                var type       = Assembly.GetExecutingAssembly().GetType(typeString);

                var methodString = CommandText.Substring(lastDotIndex + 1);
                var methodInfo   = type.GetMethod(methodString);
                var returnType   = methodInfo.ReturnType;

                var enumeratorMethodInfo = returnType.GetMethod("GetEnumerator");

                var rowType = returnType.GetGenericArguments()[0];

                if (IsClrType(Nullable.GetUnderlyingType(rowType) ?? rowType))
                {
                    cached = Tuple.Create(methodInfo, enumeratorMethodInfo, rowType, (PropertyInfo[])null);
                }
                else
                {
                    cached = Tuple.Create(methodInfo, enumeratorMethodInfo, (Type)null, rowType.GetProperties());
                }

                ReaderMethodCache.Add(CommandText, cached);
            }

            var enumerable = cached.Item1.Invoke(null, null);
            var enumerator = (IEnumerator)cached.Item2.Invoke(enumerable, null);

            return(new FakeDataReader(cached.Item3, cached.Item4, enumerator));
        }
        private void HandleExecuteScalar()
        {
            var startIndex = CommandText.IndexOf(ExecuteScalarBeginDelimiter);

            if (startIndex == -1)
            {
                return;
            }

            var endIndex = CommandText.IndexOf(ExecuteScalarEndDelimiter, startIndex);

            if (endIndex == -1)
            {
                return;
            }

            var commandText = CommandText;
            var fullText    = CommandText.Substring(startIndex, (endIndex + ExecuteScalarEndDelimiter.Length) - startIndex);

            CommandText = fullText.Substring(ExecuteScalarBeginDelimiter.Length, fullText.Length - (ExecuteScalarEndDelimiter.Length + ExecuteScalarBeginDelimiter.Length));

            var value = ExecuteScalar();

            CommandText = commandText.Replace(fullText, GetFormattedValue(value));
        }
Ejemplo n.º 5
0
        /// <summary>
        /// EXAMPLE QUERY
        /// CREATE INDEX idx_lastname
        /// ON Persons(LastName);
        /// </summary>
        protected override void ParseQuery()
        {
            // find index of open bracket in create query, where are descriptions of columns
            var openBacket = CommandText.IndexOf('(');
            // find index of close bracket in create query, where are descriptions of columns
            var closeBacket = CommandText.LastIndexOf(')');

            if (openBacket == -1 || closeBacket == -1 || openBacket == closeBacket)
            {
                throw new CreateIndexParse($"Command has incorrect signature. Check brackets.");
            }
            // get columns name
            var commandWords = CommandText?
                               .Substring(0, openBacket)
                               .Trim()
                               .Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

            if (commandWords[0].ToLower() != "create")
            {
                throw new CreateIndexParse($"Command has incorrect signature.");
            }
            if (commandWords.Length == 5)
            {
                if (commandWords[2].ToLower() != "index")
                {
                    throw new CreateIndexParse($"Command has incorrect signature.");
                }
                // find 'ON' into query
                if (commandWords[3].ToLower() != "on")
                {
                    throw new CreateIndexParse($"Command has incorrect signature.");
                }
                TableName = commandWords[4];
                IndexName = commandWords[2];
                IndexType = IndexType.DenseIndex;
            }
            else if (commandWords.Length == 6)
            {
                if (commandWords[3].ToLower() != "index")
                {
                    throw new CreateIndexParse($"Command has incorrect signature.");
                }
                throw new CreateIndexParse($"Command has not released.");
            }
            else
            {
                throw new CreateIndexParse($"Command has incorrect signature.");
            }

            var columnName = CommandText?
                             .Substring(openBacket + 1, closeBacket - 1 - openBacket);

            if (columnName.Length == 0)
            {
                throw new CreateIndexParse($"Command has incorrect signature. Can not parse columns name.");
            }

            TableName = commandWords[2].Trim();
        }
Ejemplo n.º 6
0
 private string GetSummaryText()
 {
     if (CommandText.Length <= 15)
     {
         return(CommandText);
     }
     return(string.Format("{0}...", CommandText.Substring(0, 13)));
 }
Ejemplo n.º 7
0
        internal string GetCommandTextForBatching()
        {
            if (batchableCommandText == null)
            {
                // if the command starts with insert and is "simple" enough, then
                // we can use the multi-value form of insert
                if (String.Compare(CommandText.Substring(0, 6), "INSERT", true) == 0)
                {
                    MySqlCommand cmd       = new MySqlCommand("SELECT @@sql_mode", Connection);
                    string       sql_mode  = cmd.ExecuteScalar().ToString().ToLower(CultureInfo.InvariantCulture);
                    SqlTokenizer tokenizer = new SqlTokenizer(CommandText);
                    tokenizer.AnsiQuotes       = sql_mode.IndexOf("ansi_quotes") != -1;
                    tokenizer.BackslashEscapes = sql_mode.IndexOf("no_backslash_escapes") == -1;
                    string token = tokenizer.NextToken().ToLower(CultureInfo.InvariantCulture);
                    while (token != null)
                    {
                        if (token.ToLower(CultureInfo.InvariantCulture) == "values" &&
                            !tokenizer.Quoted)
                        {
                            token = tokenizer.NextToken();
                            Debug.Assert(token == "(");
                            while (token != null && token != ")")
                            {
                                batchableCommandText += token;
                                token = tokenizer.NextToken();
                            }
                            if (token != null)
                            {
                                batchableCommandText += token;
                            }
                            token = tokenizer.NextToken();
                            if (token != null && (token == "," ||
                                                  token.ToLower(CultureInfo.InvariantCulture) == "on"))
                            {
                                batchableCommandText = null;
                                break;
                            }
                        }
                        token = tokenizer.NextToken();
                    }
                }
                if (batchableCommandText == null)
                {
                    batchableCommandText = CommandText;
                }
            }

            return(batchableCommandText);
        }
Ejemplo n.º 8
0
        protected override void ParseQuery()
        {
            // find index of open bracket in create query, where are descriptions of columns
            var openBacket = CommandText.IndexOf('(');
            // find index of close bracket in create query, where are descriptions of columns
            var closeBacket = CommandText.LastIndexOf(')');

            if (openBacket == -1 || closeBacket == -1 || openBacket == closeBacket)
            {
                throw new CreateTableParse($"Command has incorrect signature. Check brackets.");
            }
            // get command words, words befor descriptions of columns
            var commandWords = CommandText?
                               .Substring(0, openBacket)
                               .Trim()
                               .Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

            if (commandWords.Length != 3)
            {
                throw new CreateTableParse($"Command has incorrect signature. Check table name.");
            }
            // set table name and database name if format [dbname].[tableName]
            var tableAndDatabaseNames = commandWords[2].Split('.');

            if (tableAndDatabaseNames.Length == 2)
            {
                DatabaseName = tableAndDatabaseNames[0];
                TableName    = tableAndDatabaseNames[1];
            }
            else
            {
                TableName = tableAndDatabaseNames[0];
            }
            //
            Columns = CommandText?
                      .Substring(openBacket + 1, closeBacket - openBacket - 1)
                      .Trim()
                      .Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
            if (Columns.Length == 0)
            {
                throw new CreateTableParse($"Command does not have new columns description.");
            }
        }
Ejemplo n.º 9
0
        public override object ExecuteScalar()
        {
            if (ScalarMethodCache.TryGetValue(CommandText, out var cached) == false)
            {
                var lastDotIndex = CommandText.LastIndexOf('.');

                var typeString = CommandText.Substring(0, lastDotIndex);
                var type       = Assembly.GetExecutingAssembly().GetType(typeString);

                var methodString = CommandText.Substring(lastDotIndex + 1);
                cached = type.GetMethod(methodString);

                ScalarMethodCache.Add(CommandText, cached);
            }

            var value = cached.Invoke(null, null);

            return(value ?? DBNull.Value);
        }
Ejemplo n.º 10
0
        public virtual ICoreParseResult Slice(int numberOfLeadingSectionsToRemove)
        {
            if (numberOfLeadingSectionsToRemove == 0)
            {
                return(this);
            }

            if (numberOfLeadingSectionsToRemove >= Sections.Count)
            {
                return(new CoreParseResult(0, 0, string.Empty, new[] { string.Empty }, 0, new Dictionary <int, int> {
                    { 0, 0 }
                }, new HashSet <int>()));
            }

            string commandText = CommandText.Substring(SectionStartLookup[numberOfLeadingSectionsToRemove]);
            int    caretPositionWithinCommandText = CaretPositionWithinCommandText - SectionStartLookup[numberOfLeadingSectionsToRemove];

            if (caretPositionWithinCommandText < 0)
            {
                caretPositionWithinCommandText = 0;
            }

            Dictionary <int, int> sectionStartLookup = new Dictionary <int, int>();
            List <string>         sections           = new List <string>();

            for (int i = 0; i < Sections.Count - numberOfLeadingSectionsToRemove; ++i)
            {
                sectionStartLookup[i] = SectionStartLookup[numberOfLeadingSectionsToRemove + i] - SectionStartLookup[numberOfLeadingSectionsToRemove];
                sections.Add(Sections[numberOfLeadingSectionsToRemove + i]);
            }

            int selectedSection = SelectedSection - numberOfLeadingSectionsToRemove;

            if (selectedSection < 0)
            {
                selectedSection = 0;
            }

            HashSet <int> quotedSections = new HashSet <int>(_quotedSections.Where(x => x > 0).Select(x => x - 1));

            return(new CoreParseResult(caretPositionWithinCommandText, CaretPositionWithinSelectedSection, commandText, sections, selectedSection, sectionStartLookup, quotedSections));
        }
Ejemplo n.º 11
0
        internal string GetCommandTextForBatching()
        {
            if (BatchableCommandText == null)
            {
                // if the command starts with insert and is "simple" enough, then
                // we can use the multi-value form of insert
                if (String.Compare(CommandText.Substring(0, 6), "INSERT", StringComparison.OrdinalIgnoreCase) == 0)
                {
                    MySqlCommand   cmd       = new MySqlCommand("SELECT @@sql_mode", Connection);
                    string         sql_mode  = StringUtility.ToUpperInvariant(cmd.ExecuteScalar().ToString());
                    MySqlTokenizer tokenizer = new MySqlTokenizer(CommandText);
                    tokenizer.AnsiQuotes       = sql_mode.IndexOf("ANSI_QUOTES") != -1;
                    tokenizer.BackslashEscapes = sql_mode.IndexOf("NO_BACKSLASH_ESCAPES") == -1;
                    string token = StringUtility.ToLowerInvariant(tokenizer.NextToken());
                    while (token != null)
                    {
                        if (StringUtility.ToUpperInvariant(token) == "VALUES" &&
                            !tokenizer.Quoted)
                        {
                            token = tokenizer.NextToken();
                            Debug.Assert(token == "(");

                            // find matching right paren, and ensure that parens
                            // are balanced.
                            int openParenCount = 1;
                            while (token != null)
                            {
                                BatchableCommandText += token;
                                token = tokenizer.NextToken();

                                if (token == "(")
                                {
                                    openParenCount++;
                                }
                                else if (token == ")")
                                {
                                    openParenCount--;
                                }

                                if (openParenCount == 0)
                                {
                                    break;
                                }
                            }

                            if (token != null)
                            {
                                BatchableCommandText += token;
                            }
                            token = tokenizer.NextToken();
                            if (token != null && (token == "," ||
                                                  StringUtility.ToUpperInvariant(token) == "ON"))
                            {
                                BatchableCommandText = null;
                                break;
                            }
                        }
                        token = tokenizer.NextToken();
                    }
                }
                // Otherwise use the command verbatim
                else
                {
                    BatchableCommandText = CommandText;
                }
            }

            return(BatchableCommandText);
        }
        /// <summary>
        /// Writes down the C# instruction.
        /// </summary>
        /// <param name="writer">The stream on which to write.</param>
        public override void WriteCSharp(ICSharpWriter writer)
        {
            Debug.Assert(WriteDown);

            string CommandText;

            if (IsCallingNumberFeature)
            {
                CommandText = Command.CSharpText(writer, 0);
                IList <IIdentifier> ValidPath = ((IQualifiedName)Source.Command).ValidPath.Item;
                IIdentifier         FinalFeatureIdentifier = ValidPath[ValidPath.Count - 1];

                if (FinalFeatureIdentifier.ValidText.Item == "Increment")
                {
                    CommandText = CommandText.Substring(0, CommandText.Length - 10);
                    writer.WriteIndentedLine($"{CommandText}++;");
                    return;
                }

                else if (FinalFeatureIdentifier.ValidText.Item == "Decrement")
                {
                    CommandText = CommandText.Substring(0, CommandText.Length - 10);
                    writer.WriteIndentedLine($"{CommandText}--;");
                    return;
                }
            }

            bool IsAgent = !(FinalFeature is ICSharpProcedureFeature);

            if (IsAgent)
            {
                IIdentifier AgentIdentifier     = (IIdentifier)Source.Command.Path[Source.Command.Path.Count - 1];
                string      AgentIdentifierText = CSharpNames.ToCSharpIdentifier(AgentIdentifier.ValidText.Item);

                if (Source.Command.Path.Count > 1)
                {
                    CommandText = Command.CSharpText(writer, 1);
                }
                else
                {
                    CommandText = "this";
                }

                if (FeatureCall.ArgumentList.Count > 0)
                {
                    ICSharpExpressionContext ExpressionContext = new CSharpExpressionContext();
                    string ArgumentListText = CSharpArgument.CSharpArgumentList(writer, ExpressionContext, FeatureCall);

                    writer.WriteIndentedLine($"{AgentIdentifierText}({CommandText}, {ArgumentListText});");
                }
                else
                {
                    writer.WriteIndentedLine($"{AgentIdentifierText}({CommandText});");
                }
            }
            else
            {
                CommandText = Command.CSharpText(writer, SkipLastInPath ? 1 : 0);
                ICSharpExpressionContext ExpressionContext = new CSharpExpressionContext();
                string ArgumentListText = CSharpArgument.CSharpArgumentList(writer, ExpressionContext, FeatureCall);

                writer.WriteIndentedLine($"{CommandText}({ArgumentListText});");
            }
        }
Ejemplo n.º 13
0
        void CommandReceived(IAsyncResult arg)
        {
            _activecommand = false;
            int CommandSize = 0;

            try { CommandSize = _clientSocket.EndReceive(arg); }
            catch { }
            if (CommandSize == 0)
            {
                Disconnect();
                //return;
            }

            // Wait for the next command to be sent by the client
            try
            {
                _clientSocket.BeginReceive(_portBuffer, 0, _portBuffer.Length, SocketFlags.None, new AsyncCallback(CommandReceived), null);
            }
            catch
            {
                Disconnect();
                return;
            }

            _lastcmdtime = DateTime.Now;
            string CommandText;

            if (_utf8)
            {
                CommandText = Encoding.UTF8.GetString(_portBuffer, 0, CommandSize).TrimStart(' ');
            }
            else
            {
                CommandText = Encoding.ASCII.GetString(_portBuffer, 0, CommandSize).TrimStart(' ');
            }
            string CmdArguments = null, Command = null;
            int    End = 0;

            if ((End = CommandText.IndexOf(' ')) == -1)
            {
                End = (CommandText = CommandText.Trim()).Length;
            }
            else
            {
                CmdArguments = CommandText.Substring(End).TrimStart(' ');
            }
            Command = CommandText.Substring(0, End).ToUpper();

            if (CmdArguments != null && CmdArguments.EndsWith("\r\n"))
            {
                CmdArguments = CmdArguments.Substring(0, CmdArguments.Length - 2);
            }
            bool CommandExecued = false;

            switch (Command)
            {
            case "USER":
                _activecommand = true;
                if (CmdArguments != null && CmdArguments.Length > 0)
                {
                    SendMessage("331 Password required!");
                    _connuser = CmdArguments;
                }
                CommandExecued = true;
                break;

            case "PASS":
                _activecommand = true;
                if (_connuser == "")
                {
                    SendMessage("503 Invalid User Name");
                    return;
                }
                if (_server.Users[_connuser] != null)
                {
                    if (_server.Users[_connuser].SHA1Password == HelperFunctions.SHA1Hash(CmdArguments))
                    {
                        _isAuthenticated = true;
                        _currentDir      = "/";
                        _currentperms    = _server.Users.GetPermissions(_connuser);
                        if (string.IsNullOrEmpty(_server.Users[_connuser].Startupdir) || _server.Users[_connuser].Startupdir == "/")
                        {
                            _localpath = _server.StartupDir;
                        }
                        else
                        {
                            _localpath = _server.Users[_connuser].Startupdir;
                        }
                        _server.Call_Log(new FTPLogEventArgs(FTPLogEventType.UserConnect, _connuser, true, 230, "none"));
                        SendMessage("230 Authentication Successful");
                    }
                    else
                    {
                        SendMessage("530 Authentication Failed!");
                        _server.Call_Log(new FTPLogEventArgs(FTPLogEventType.UserConnect, _connuser, false, 530, "none"));
                    }
                }
                else
                {
                    SendMessage("530 Authentication Failed!");
                    _server.Call_Log(new FTPLogEventArgs(FTPLogEventType.UserConnect, _connuser, false, 530, "none"));
                }
                CommandExecued = true;
                break;
            }
            if (!CommandExecued)
            {
                if (!_isAuthenticated)
                {
                    SendMessage("530 Access Denied! Authenticate first");
                    return;
                }
                switch (Command.ToUpper())
                {
                case "CWD":
                    _activecommand = true;
                    CWD(CmdArguments);
                    break;

                case "CDUP":
                    _activecommand = true;
                    string[] pathParts = _currentDir.Split('/');
                    if (pathParts.Length > 1)
                    {
                        _currentDir = "";
                        for (int i = 0; i < (pathParts.Length - 2); i++)
                        {
                            _currentDir += pathParts[i] + "/";
                        }
                        if (_currentDir.Length == 0)
                        {
                            _currentDir = "/";
                        }
                    }
                    SendMessage("250 CDUP command successful.");
                    break;

                case "QUIT":
                    _activecommand = true;
                    SendMessage("221 FTP server signing off");
                    Disconnect();
                    break;

                case "PWD":
                    _activecommand = true;
                    SendMessage("257 \"" + _currentDir + "\"");
                    break;

                case "PORT":
                    _activecommand = true;
                    PORT(CmdArguments);     //done
                    break;

                case "PASV":
                    _activecommand = true;
                    PASV(CmdArguments);     //done
                    break;

                case "TYPE":
                    _activecommand = true;
                    TYPE(CmdArguments);     //done
                    break;

                case "SYST":
                    _activecommand = true;
                    SendMessage("215 Windows_NT");
                    break;

                case "NOOP":
                    _activecommand = true;
                    SendMessage("200 OK");
                    break;

                case "RETR":
                    _activecommand = true;
                    RETR(CmdArguments);
                    break;

                case "STOR":
                    _activecommand = true;
                    STOR(CmdArguments, false);
                    break;

                case "APPE":
                    _activecommand = true;
                    APPE(CmdArguments);
                    break;

                case "RNFR":
                    _activecommand = true;
                    RNFR(CmdArguments);
                    break;

                case "RNTO":
                    _activecommand = true;
                    RNTO(CmdArguments);
                    break;

                case "DELE":
                    _activecommand = true;
                    DELE(CmdArguments);
                    break;

                case "RMD":
                    _activecommand = true;
                    RMD(CmdArguments);
                    break;

                case "MKD":
                    _activecommand = true;
                    MKD(CmdArguments);
                    break;

                case "LIST":
                    _activecommand = true;
                    LIST(_currentDir);
                    break;

                case "NLST":
                    _activecommand = true;
                    NLST(CmdArguments);
                    break;

                /*case "CLNT":
                 *  break;*/
                case "MDTM":
                    _activecommand = true;
                    MDTM(CmdArguments);
                    break;

                case "SIZE":
                    _activecommand = true;
                    SIZE(CmdArguments);
                    break;

                case "OPTS":
                    _activecommand = true;
                    OPTS(CmdArguments);
                    break;

                case "REIN":
                    _activecommand = true;
                    REIN(CmdArguments);
                    break;

                case "STOU":
                    _activecommand = true;
                    STOR(CmdArguments, true);
                    break;

                case "ABOR":
                case "SHUTDOWN":
                    if (_datasocket != null && _datasocket.Connected)
                    {
                        _datasocket.Close();
                    }
                    _datasocket = null;
                    GC.Collect();
                    SendMessage("200 Data transfer aborted");
                    _server.Call_Log(new FTPLogEventArgs(FTPLogEventType.Abort, _connuser, true, 200));
                    break;

                case "FEAT":
                    SendMessage("  SIZE");
                    SendMessage("  MTDM");
                    SendMessage("211 Feature list end");
                    _server.Call_Log(new FTPLogEventArgs(FTPLogEventType.FeatureList, _connuser, true, 211));
                    break;

                default:
                    SendMessage("500 Unknown Command.");
                    _server.Call_Log(new FTPLogEventArgs(FTPLogEventType.UnknownCommand, _connuser, true, 500, Command, CmdArguments));
                    break;

                    //	case "STAT":
                    //		break;

                    //	case "HELP":
                    //		break;

                    //	case "REST":
                    //		break;
                }
            }
        }