Exemple #1
0
        public static string FormatSqlCe(this Expression expression, QueryLanguage language)
        {
            var formatter = new SqlCeFormatter(language);

            formatter.Visit(expression);
            return(formatter.ToString());
        }
Exemple #2
0
        /// <summary>
        /// Writes to string.
        /// </summary>
        /// <param name="language">The language.</param>
        /// <param name="expression">The expression.</param>
        /// <returns></returns>
        public static string WriteToString(QueryLanguage language, Expression expression)
        {
            StringWriter sw = new StringWriter();

            Write(sw, language, expression);
            return(sw.ToString());
        }
Exemple #3
0
        public static string Format(Expression expression, QueryLanguage language)
        {
            VfpFormatter formatter = new VfpFormatter(language);

            formatter.Visit(expression);
            return(formatter.ToString());
        }
 public bool Compile(CodeDomProvider codeProvider, string source, TempFileRef dataContextAssembly, QueryLanguage queryKind, string compilerOptions)
 {
     if (this.IsMyExtensions)
     {
         string directoryName = Path.GetDirectoryName(MyExtensions.QueryFilePath);
         if (!Directory.Exists(directoryName))
         {
             Directory.CreateDirectory(directoryName);
         }
         TempFileRef ref2 = new TempFileRef(Path.ChangeExtension(MyExtensions.QueryFilePath, ".dll")) {
             AutoDelete = false
         };
         this.OutputFile = ref2;
         TempFileRef ref3 = new TempFileRef(Path.ChangeExtension(MyExtensions.QueryFilePath, ".pdb")) {
             AutoDelete = false
         };
         this.PDBFile = ref3;
     }
     else
     {
         this.OutputFile = TempFileRef.GetRandom("query", ".dll");
         this.PDBFile = new TempFileRef(Path.ChangeExtension(this.OutputFile.FullPath, ".pdb"));
     }
     List<string> references = new List<string>(this.References);
     if (!((dataContextAssembly == null) || string.IsNullOrEmpty(dataContextAssembly.FullPath)))
     {
         references.Add(dataContextAssembly.FullPath);
     }
     return base.Compile(codeProvider, references, source.ToString(), this.OutputFile.FullPath, compilerOptions);
 }
Exemple #5
0
        /// <summary>
        /// Projects the columns.
        /// </summary>
        /// <param name="language">The language.</param>
        /// <param name="expression">The expression.</param>
        /// <param name="existingColumns">The existing columns.</param>
        /// <param name="newAlias">The new alias.</param>
        /// <param name="existingAliases">The existing aliases.</param>
        /// <returns></returns>
        public static ProjectedColumns ProjectColumns(QueryLanguage language, Expression expression, IEnumerable <ColumnDeclaration> existingColumns, TableAlias newAlias, IEnumerable <TableAlias> existingAliases)
        {
            ColumnProjector projector = new ColumnProjector(language, expression, existingColumns, newAlias, existingAliases);
            Expression      expr      = projector.Visit(expression);

            return(new ProjectedColumns(expr, projector.columns.AsReadOnly()));
        }
Exemple #6
0
        internal static HashSet <Expression> Nominate(QueryLanguage language, Expression expression)
        {
            Nominator nominator = new Nominator(language);

            nominator.Visit(expression);
            return(nominator.candidates);
        }
Exemple #7
0
        IUrlProvider IUrlProvider.SetLanguage(QueryLanguage Language)
        {
            const string queryIdentifier = "lang=";
            string       queryParameter  = string.Empty;

            switch (Language)
            {
            case QueryLanguage.German:
                queryParameter = "de";
                break;

            case QueryLanguage.English:
                queryParameter = "en";
                break;

            case QueryLanguage.French:
                queryParameter = "fr";
                break;

            case QueryLanguage.Turkish:
                queryParameter = "tr";
                break;
            }
            AppendQuery(string.Concat(queryIdentifier, queryParameter));
            return(this);
        }
Exemple #8
0
        private static string GetSourceExtension(QueryLanguage kind)
        {
            switch (kind)
            {
            case QueryLanguage.Expression:
            case QueryLanguage.Statements:
            case QueryLanguage.Program:
                return(".cs");

            case QueryLanguage.VBExpression:
            case QueryLanguage.VBStatements:
            case QueryLanguage.VBProgram:
                return(".vb");

            case QueryLanguage.FSharpExpression:
            case QueryLanguage.FSharpProgram:
                return(".fsx");

            case QueryLanguage.SQL:
            case QueryLanguage.ESQL:
                return(".sql");

            default:
                return(".txt");
            }
        }
Exemple #9
0
        static void GenerateCsx(string queryFilePath,
                                string packagesPath, QueryLanguage queryKind, string source,
                                IEnumerable <string> imports, IEnumerable <Reference> references,
                                IndentingLineWriter writer)
        {
            var body = queryKind == QueryLanguage.Expression
                     ? string.Join(Environment.NewLine, "System.Console.WriteLine(", source, ");")
                     : queryKind == QueryLanguage.Program
                     ? source + Environment.NewLine + "Main();"
                     : source;

            var rs = references.ToArray();

            File.WriteAllLines(Path.ChangeExtension(queryFilePath, ".csx"),
                               from lines in new[]
            {
                from r in rs
                select $"#r \"{r.Path}\"",

                Seq.Return(string.Empty),

                from ns in imports
                select $"using {ns};",

                Seq.Return(body, string.Empty),
            }
                               from line in lines
                               select line);

            // TODO User-supplied csi.cmd

            GenerateBatch(LoadTextResource("csi.cmd"), queryFilePath, packagesPath, rs);
        }
Exemple #10
0
        // MySql
        private static void InsertIntoMySqlDatabase(MySqlConnection con, QueryLanguage ql)
        {
            try
            {
                con.Open();
            }
            catch (MySqlException)
            {
                MessageBox.Show("Unable to open connection to MySQL Database while attempting to insert data. Please recheck your credentials and try again", "Potential User Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                mw.ResetButtons();
            }


            List <BibleCollection> LanguageCollection = new List <BibleCollection>();

            LanguageCollection = MemoryStorage.FullDataCollection[(int)ql].BibleCollection;

            StringBuilder sb = new StringBuilder();

            bool firstStringFinished = false;

            foreach (var fc in LanguageCollection)
            {
                if (!firstStringFinished)
                {
                    sb.Append("INSERT INTO " + ql.ToString() + "(Book, Chapter, Verse, Word) " + Environment.NewLine + " VALUES('" + fc.CurrentBook + "', " + fc.Chapter + ", " + fc.Verse + ", \"" + fc.Word + "\")" + Environment.NewLine);
                    firstStringFinished = true;
                }
                else
                {
                    sb.Append(", ('" + fc.CurrentBook + "', " + fc.Chapter + ", " + fc.Verse + ", \"" + fc.Word + "\")" + Environment.NewLine);
                }
                MemoryStorage.CurrentQuery++;
                mw.UpdateQueryProgress();
            }
            sb.Append(";" + Environment.NewLine + Environment.NewLine);

            using (StreamWriter w = new StreamWriter("debug-me.sql", true))
            {
                w.Write(sb.ToString());
            }

            using (MySqlCommand cmd = new MySqlCommand(sb.ToString()))
            {
                cmd.Connection     = con;
                cmd.CommandTimeout = 999999;
                try
                {
                    cmd.ExecuteNonQueryAsync();
                }
                catch (MySqlException mse)
                {
                    MessageBox.Show("Unable to insert data into MySQL database:" + Environment.NewLine + Environment.NewLine + mse, "Potential User Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    mw.ResetButtons();
                }
            }

            con.Close();
        }
Exemple #11
0
 public DbEntityProvider(DbConnection connection, QueryLanguage language, QueryMapping mapping, QueryPolicy policy) : base(language, mapping, policy)
 {
     if (connection == null)
     {
         throw new InvalidOperationException("Connection not specified");
     }
     this.connection = connection;
 }
Exemple #12
0
 private QueryBinder(QueryMapper mapper, Expression root)
 {
     this.mapper     = mapper;
     this.language   = mapper.Translator.Linguist.Language;
     this.map        = new Dictionary <ParameterExpression, Expression>();
     this.groupByMap = new Dictionary <Expression, GroupByInfo>();
     this.root       = root;
 }
Exemple #13
0
 public SessionInfo(string userID, string password, string defaultLibraryName, bool defaultUseDTC, QueryLanguage language) : base()
 {
     UserID             = userID;
     Password           = password;
     DefaultLibraryName = defaultLibraryName;
     _defaultUseDTC     = defaultUseDTC;
     _language          = language;
 }
Exemple #14
0
        public static SelectExpression AddRedundantSelect(this SelectExpression sel, QueryLanguage language, TableAlias newAlias)
        {
            var newColumns = from d
                             in sel.Columns
                             select new ColumnDeclaration(d.Name, new ColumnExpression(d.Expression.Type, newAlias, d.Name));

            var newFrom = new SelectExpression(newAlias, sel.Columns, sel.From, sel.Where, sel.OrderBy, sel.GroupBy, sel.IsDistinct, sel.Skip, sel.Take, sel.IsReverse);

            return(new SelectExpression(sel.Alias, newColumns, newFrom, null, null, null, false, null, null, false));
        }
        public static string Format(Expression expression, QueryLanguage language)
        {
            var formatter = new AccessFormatter(language);

            if (formatter != null)
            {
                formatter.FormatWithParameters(expression);
            }

            return(formatter.ToString());
        }
        public static string Format(Expression expression, QueryLanguage language)
        {
            var formatter = new OracleFormatter(language);

            if (formatter != null)
            {
                formatter.Visit(expression);
            }

            return(formatter.ToString());
        }
Exemple #17
0
 /// <summary>
 /// Constructs a NDOQuery object
 /// </summary>
 /// <param name="pm">The PersistenceManager used to manage the objects.</param>
 /// <param name="queryExpression">A NDOql or SQL expression.</param>
 /// <param name="hollowResults">Determines, if the objects should be fetched in the hollow state (true) or filled with data (false).</param>
 /// <param name="queryLanguage">Determines, if the query is a SQL pass-through query or a NDOql expression.</param>
 public NDOQuery(PersistenceManager pm, string queryExpression, bool hollowResults, QueryLanguage queryLanguage)
 {
     this.pm = pm;
     if (pm == null)
     {
         throw new ArgumentException("Parameter is null", "pm");
     }
     this.mappings        = pm.mappings;
     this.queryExpression = queryExpression;
     this.hollowResults   = hollowResults;
     this.queryLanguage   = queryLanguage;
 }
Exemple #18
0
        public override object InternalExecute(Program program, object[] arguments)
        {
            string libraryName;
            string documentName;

            if (arguments.Length == 2)
            {
                libraryName  = (string)arguments[0];
                documentName = (string)arguments[1];
            }
            else
            {
                libraryName  = program.Plan.CurrentLibrary.Name;
                documentName = (string)arguments[0];
            }

            FrontendDevice device = FrontendDevice.GetFrontendDevice(program);

            string documentType = device.GetDocumentType(program, libraryName, documentName);

            QueryLanguage saveLanguage = program.ServerProcess.ProcessInfo.Language;

            if (documentType == "sql")
            {
                program.ServerProcess.ProcessInfo.Language = QueryLanguage.RealSQL;
            }

            try
            {
                SystemExecuteNode.ExecuteScript
                (
                    program.ServerProcess,
                    program,
                    this,
                    device.LoadDocument
                    (
                        program,
                        libraryName,
                        documentName
                    ),
                    new DAE.Debug.DebugLocator("doc:" + libraryName + ":" + documentName, 1, 1)
                );
            }
            finally
            {
                if (documentType == "sql")
                {
                    program.ServerProcess.ProcessInfo.Language = saveLanguage;
                }
            }

            return(null);
        }
Exemple #19
0
        // Sql Server
        private static void CheckIfSqlServerTableExists(SqlConnection con, QueryLanguage ql)
        {
            try
            {
                con.Open();
            }
            catch (SqlException)
            {
                MessageBox.Show("Unable to open connection to SQL Server Database. Please recheck your Connection String and try again.", "Potential User Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                mw.ResetButtons();
            }

            string Query = Queries.SqlServer.CheckIfTableExists(ql);

            using (SqlCommand cmd = new SqlCommand(Query))
            {
                try
                {
                    cmd.Connection = con;
                }
                catch (SqlException)
                {
                    MessageBox.Show("Unable to open connection to SQL Server Database. Please recheck your Connection String and try again.", "Potential User Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    mw.ResetButtons();
                }
                SqlDataReader r = cmd.ExecuteReader();

                while (r.Read())
                {
                    if (r.GetString(0).Length > 0)
                    {
                        SqlServerTableLength = r.GetString(0).Length;
                    }
                }

                r.Close();

                if (SqlServerTableLength == 0)
                {
                    cmd.CommandText = Queries.SqlServer.GetTableCreationString(ql);
                    try
                    {
                        cmd.ExecuteNonQuery();
                    }
                    catch (SqlException se)
                    {
                        MessageBox.Show("Error when checking if table exists in SQL Server Database: " + Environment.NewLine + Environment.NewLine + se, "Unable to check table", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                        mw.ResetButtons();
                    }
                }
            }
            con.Close();
        }
Exemple #20
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="connection"></param>
 /// <param name="policy"></param>
 /// <param name="log"></param>
 /// <param name="dataObjectType"></param>
 /// <param name="dataContext"></param>
 public DataQueryProvider(
     DbConnection connection, QueryPolicy policy, TextWriter log,
     Type dataObjectType, IDataContextBase dataContext)
 {
     this.connection     = connection;
     this.policy         = policy;
     this.mapping        = policy.Mapping;
     this.language       = mapping.Language;
     this.log            = log;
     this.dataObjectType = dataObjectType;
     this.dataContext    = dataContext;
 }
Exemple #21
0
        public EntityProvider(QueryLanguage language, QueryMapping mapping, QueryPolicy policy)
        {
            if (language == null)
            {
                throw new ArgumentNullException(nameof(language));
            }

            Language = language;
            Mapping  = mapping ?? new AttributeMapping();
            Policy   = policy ?? QueryPolicy.Default;
            tables   = new Dictionary <MappingEntity, IEntityTable>();
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="HqlBasedQuery"/> class.
 /// </summary>
 /// <param name="targetType">Type of the target.</param>
 /// <param name="queryLanguage">The query language.</param>
 /// <param name="query">The query.</param>
 /// <param name="positionalParameters">The positional parameters.</param>
 public HqlBasedQuery(Type targetType, QueryLanguage queryLanguage, string query, params object[] positionalParameters)
     : this(targetType, queryLanguage, query)
 {
     if (positionalParameters != null && positionalParameters.Length > 0)
     {
         int i = 0;
         foreach (object value in positionalParameters)
         {
             ValueAndTypeTuple valueAndTypeTuple = ValueAndTypeTuple.Wrap(value);
             AddModifier(new QueryParameter(i++, valueAndTypeTuple.Value, valueAndTypeTuple.Type));
         }
     }
 }
Exemple #23
0
        public DbEntityProvider(DataContext context, QueryLanguage language, QueryMapping mapping, QueryPolicy policy) : base(context, language, mapping, policy)
        {
            this.isolation              = IsolationLevel.ReadCommitted;
            this.nConnectedActions      = 0;
            this.actionOpenedConnection = false;
            DbConnection connection = context.Connection;

            if (connection == null)
            {
                throw new InvalidOperationException("Connection not specified");
            }
            this.connection = connection;
        }
        // MySQL
        public static void Open(Forms.frm_MainWindow _mw, string server, string database, string username, string password, QueryLanguage ql)
        {
            mw = _mw;
            using (MySqlConnection con = new MySqlConnection("Server=" + server + ";Database=" + database + ";Uid=" + username + ";Pwd=" + password + "; CharSet=utf8;"))
            {
                // Checks if table exists or not. If it doesn't, create it. If not, continue.
                CheckIfMySqlTableExists(con, database, ql);

                MySqlTableLength = 0;
                // Inserts data into database
                InsertIntoMySqlDatabase(con, ql);
            }
        }
Exemple #25
0
        // SQL Server
        public static void Open(Forms.frm_MainWindow _mw, string connectionString, QueryLanguage ql)
        {
            mw = _mw;
            using (SqlConnection con = new SqlConnection(connectionString))
            {
                // Checks if table exists or not. If it doesn't, create it. If not, continue.
                CheckIfSqlServerTableExists(con, ql);

                SqlServerTableLength = 0;

                // Inserts data into database
                InsertIntoSqlServerDatabase(con, ql);
            }
        }
        // SQL Server
        public static void Open(Forms.frm_MainWindow _mw, string connectionString, QueryLanguage ql)
        {
            mw = _mw;
            using (SqlConnection con = new SqlConnection(connectionString))
            {
                // Checks if table exists or not. If it doesn't, create it. If not, continue.
                CheckIfSqlServerTableExists(con, ql);

                SqlServerTableLength = 0;

                // Inserts data into database
                InsertIntoSqlServerDatabase(con, ql);
            }
        }
 public static string GetTableCreationString(QueryLanguage ql)
 {
     StringBuilder sb = new StringBuilder();
     sb.Append("IF OBJECT_ID('[dbo].[" + ql.ToString() + "]', 'U') IS NOT NULL DROP TABLE [dbo].[" + ql.ToString() + "]; ");
     sb.Append("CREATE TABLE [dbo].[" + ql.ToString() + "] (");
     sb.Append("    [Id]      INT            IDENTITY (1, 1) NOT NULL,");
     sb.Append("    [Book]    NVARCHAR (20)   NOT NULL,");
     sb.Append("    [Chapter] INT	    NOT NULL,");
     sb.Append("    [Verse]   INT	    NOT NULL,");
     sb.Append("    [Word]    NVARCHAR (2000) NOT NULL,");
     sb.Append("    PRIMARY KEY CLUSTERED ([Id] ASC)");
     sb.Append(");");
     return sb.ToString();
 }
 public static string EscapeStringForLanguage(string input, QueryLanguage language)
 {
     CodeDomProvider provider;
     StringWriter writer = new StringWriter();
     if (language <= QueryLanguage.Program)
     {
         provider = new CSharpCodeProvider();
     }
     else
     {
         provider = new VBCodeProvider();
     }
     provider.GenerateCodeFromExpression(new CodePrimitiveExpression(input), writer, null);
     return writer.GetStringBuilder().ToString();
 }
Exemple #29
0
        public static string GetTableCreationString(QueryLanguage ql)
        {
            StringBuilder sb = new StringBuilder();

            sb.Append("IF OBJECT_ID('[dbo].[" + ql.ToString() + "]', 'U') IS NOT NULL DROP TABLE [dbo].[" + ql.ToString() + "]; ");
            sb.Append("CREATE TABLE [dbo].[" + ql.ToString() + "] (");
            sb.Append("    [Id]      INT            IDENTITY (1, 1) NOT NULL,");
            sb.Append("    [Book]    NVARCHAR (20)   NOT NULL,");
            sb.Append("    [Chapter] INT	    NOT NULL,");
            sb.Append("    [Verse]   INT	    NOT NULL,");
            sb.Append("    [Word]    NVARCHAR (2000) NOT NULL,");
            sb.Append("    PRIMARY KEY CLUSTERED ([Id] ASC)");
            sb.Append(");");
            return(sb.ToString());
        }
Exemple #30
0
        private bool Populate(string data)
        {
            XElement element;
            int      lineNumber;

            if (!_validQueryHeader.IsMatch(data))
            {
                return(false);
            }
            try
            {
                XmlParserContext context     = new XmlParserContext(null, null, null, XmlSpace.None);
                Stream           xmlFragment = new MemoryStream(Encoding.UTF8.GetBytes(data));
                XmlTextReader    reader      = new XmlTextReader(xmlFragment, XmlNodeType.Element, context);
                reader.MoveToContent();
                XmlReader     reader2 = reader.ReadSubtree();
                StringBuilder output  = new StringBuilder();
                using (XmlWriter writer = XmlWriter.Create(output))
                {
                    writer.WriteNode(reader2, true);
                }
                element    = XElement.Parse(output.ToString());
                lineNumber = reader.LineNumber;
            }
            catch (XmlException)
            {
                return(false);
            }
            if (element.Attribute("Kind") != null)
            {
                try
                {
                    this._language = (QueryLanguage)Enum.Parse(typeof(QueryLanguage), (string)element.Attribute("Kind"), true);
                }
                catch (ArgumentException)
                {
                }
            }
            this._metaData = element;
            StringReader reader3 = new StringReader(data);

            for (int i = 0; i < lineNumber; i++)
            {
                reader3.ReadLine();
            }
            this._text = reader3.ReadToEnd().Trim();
            return(true);
        }
Exemple #31
0
        // Sql Server. Extremely slow. Switch to StringBuilder or Bulk Insert.
        private static void InsertIntoSqlServerDatabase(SqlConnection con, QueryLanguage ql)
        {
            try
            {
                con.Open();
            }
            catch (SqlException se)
            {
                MessageBox.Show("Unable to open connection to SQL Server database while attempting to insert data:" + Environment.NewLine + Environment.NewLine + se, "Potential User Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                mw.ResetButtons();
            }

            List <BibleCollection> LanguageCollection = new List <BibleCollection>();

            LanguageCollection = MemoryStorage.FullDataCollection[(int)ql].BibleCollection;

            StringBuilder sb = new StringBuilder();


            int currentQuery = 0;

            foreach (var fc in LanguageCollection)
            {
                sb.Append("INSERT INTO " + ql.ToString() + "(Book, Chapter, Verse, Word) VALUES(N'" + fc.CurrentBook + "', " + fc.Chapter + ", " + fc.Verse + ", N'" + fc.Word.Replace("'", "''") + "');" + Environment.NewLine);

                currentQuery++;
                MemoryStorage.CurrentQuery++;
                mw.UpdateQueryProgress();
            }

            sb.Append(";" + Environment.NewLine + Environment.NewLine);

            using (SqlCommand cmd = new SqlCommand(sb.ToString(), con))
            {
                try
                {
                    cmd.ExecuteNonQuery();
                }
                catch (SqlException se)
                {
                    MessageBox.Show("Unable to insert data into SQL Server Database:" + Environment.NewLine + Environment.NewLine + se, "Potential User Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    mw.ResetButtons();
                }
                MemoryStorage.CurrentQuery++;
                mw.UpdateQueryProgress();
            }
            con.Close();
        }
Exemple #32
0
        public static string EscapeStringForLanguage(string input, QueryLanguage language)
        {
            CodeDomProvider provider;
            StringWriter    writer = new StringWriter();

            if (language <= QueryLanguage.Program)
            {
                provider = new CSharpCodeProvider();
            }
            else
            {
                provider = new VBCodeProvider();
            }
            provider.GenerateCodeFromExpression(new CodePrimitiveExpression(input), writer, null);
            return(writer.GetStringBuilder().ToString());
        }
Exemple #33
0
 public ScriptExecutor
 (
     IServerSession session,
     String script,
     QueryLanguage language,
     ReportScriptProgressHandler executeProgress,
     ExecuteFinishedHandler executeFinished,
     DebugLocator locator
 )
 {
     _session         = session;
     _script          = script;
     _language        = language;
     _executeFinished = executeFinished;
     _executeProgress = executeProgress;
     _locator         = locator;
 }
Exemple #34
0
 private ColumnProjector(QueryLanguage language, Expression expression, IEnumerable <ColumnDeclaration> existingColumns, TableAlias newAlias, IEnumerable <TableAlias> existingAliases)
 {
     this.language        = language;
     this.newAlias        = newAlias;
     this.existingAliases = new HashSet <TableAlias>(existingAliases);
     this.map             = new Dictionary <ColumnExpression, ColumnExpression>();
     if (existingColumns != null)
     {
         this.columns     = new List <ColumnDeclaration>(existingColumns);
         this.columnNames = new HashSet <string>(existingColumns.Select(c => c.Name));
     }
     else
     {
         this.columns     = new List <ColumnDeclaration>();
         this.columnNames = new HashSet <string>();
     }
     this.candidates = Nominator.Nominate(language, expression);
 }
        // MySql
        private static void CheckIfMySqlTableExists(MySqlConnection con, string dbName, QueryLanguage ql)
        {
            try
            {
                con.Open();
            }
            catch (MySqlException mse)
            {
                MessageBox.Show("Unable to open connection to MySQL Database. Please recheck your credentials and try again:\n\n" + mse, "Potential User Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                mw.ResetButtons();
            }

            using (MySqlCommand cmd = new MySqlCommand(Queries.MySql.CheckIfTableExists(ql)))
            {
                cmd.Connection = con;

                MySqlDataReader r = cmd.ExecuteReader();
                while (r.Read())
                {
                    if (r.GetString(0).Length > 0)
                    {
                        MySqlTableLength = r.GetString(0).Length;
                    }
                }

                r.Close();

                if (MySqlTableLength == 0)
                {
                    cmd.CommandText = Queries.MySql.GetTableCreationString(ql);
                    try
                    {
                        cmd.ExecuteNonQuery();
                    }
                    catch (MySqlException mse)
                    {
                        MessageBox.Show("Error when checking if table exists in MySQL Database: " + Environment.NewLine + Environment.NewLine + mse, "Unable to check table", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                        mw.ResetButtons();
                    }
                }
            }
            con.Close();

        }
Exemple #36
0
 public EntityProvider(QueryLanguage language, QueryMapping mapping, QueryPolicy policy)
 {
     if (language == null)
     {
         throw new InvalidOperationException("Language not specified");
     }
     if (mapping == null)
     {
         throw new InvalidOperationException("Mapping not specified");
     }
     if (policy == null)
     {
         throw new InvalidOperationException("Policy not specified");
     }
     this.language = language;
     this.mapping  = mapping;
     this.policy   = policy;
     this.tables   = new Dictionary <MappingEntity, IEntityTable>();
 }
Exemple #37
0
 public static string GetMyExtensionsTemplate(QueryLanguage language)
 {
     return "void Main()\r\n{\r\n\t// Write code to test your extensions here. Press F5 to compile and run.\r\n}\r\n\r\npublic static class MyExtensions\r\n{\r\n\t// Write custom extension methods here. They will be available to all queries.\r\n\t\r\n}\r\n\r\n// You can also define non-static classes, enums, etc.";
 }
 public static Expression Rewrite(QueryLanguage language, Expression expression)
 {
     return new ClientJoinedProjectionRewriter(language).Visit(expression);
 }
 private ClientJoinedProjectionRewriter(QueryLanguage language)
 {
     this.language = language;
 }
 // This is all local. If you want to SQL inject yourself, be my guest. Neither MysQL nor SQL Server allow table names to be parameters. Only values.
 public static string CheckIfTableExists(QueryLanguage ql)
 {
     return "SELECT name FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[" + ql.ToString() + "]') AND type in (N'U')";
 }
Exemple #41
0
		/// <summary>
		/// Creates a new <c>SimpleQuery</c>.
		/// </summary>
		public SimpleQuery(Type returnType, QueryLanguage queryLanguage, string query, params object[] positionalParameters)
			: this(returnType, returnType, queryLanguage, query, positionalParameters)
		{
		}
 internal QueryControl(RunnableQuery q, SchemaTree schemaTree)
 {
     EventHandler onClick = null;
     EventHandler handler2 = null;
     EventHandler handler3 = null;
     EventHandler handler4 = null;
     SplitterCancelEventHandler handler5 = null;
     this._browserHidden = true;
     Timer timer = new Timer {
         Interval = 0x2710,
         Enabled = true
     };
     this._autoSaveTimer = timer;
     this._executionTrackingTimer = new Timer();
     this._pluginWinButtons = new List<ToolStripButton>();
     this._query = new RunnableQuery();
     this.NextQueryRequest = delegate (object sender, EventArgs e) {
     };
     this.PreviousQueryRequest = delegate (object sender, EventArgs e) {
     };
     this._lambdaData = new MemoryStream();
     this._ilDirty = true;
     this._ilData = new MemoryStream();
     this._queryCount = 0;
     Timer timer2 = new Timer {
         Interval = 200
     };
     this._refreshTimer = timer2;
     Timer timer3 = new Timer {
         Interval = 200
     };
     this._clockTimer = timer3;
     this._firstResultsShow = true;
     this._lastQueryKind = QueryLanguage.SQL;
     this._suppressPullCount = 0;
     this._random = new Random();
     this.components = null;
     this._query = q;
     this._schemaTree = schemaTree;
     try
     {
         this.Font = FontManager.GetDefaultFont();
     }
     catch
     {
     }
     this.InitializeComponent();
     this.CheckIsMyExtensions();
     this._pluginWinManager = new PluginWindowManager(this);
     this._pluginWinButtonMenu = new ContextMenuStrip(this.components);
     if (onClick == null)
     {
         onClick = (sender, e) => this.CloseCurrentVisualizer();
     }
     this._pluginWinButtonMenu.Items.Add("Close visualizer (Shift+F4 or Middle-Click or Ctrl+Click)", Resources.Delete, onClick);
     if (this.btnExecute.Height > 0x20)
     {
         this.btnExecute.Height -= 3;
         this.cboLanguage.Margin = new Padding(this.cboLanguage.Margin.Left, 2, this.cboLanguage.Margin.Right, 4);
         this.cboDb.Margin = new Padding(this.cboDb.Margin.Left, 2, this.cboDb.Margin.Right, 4);
     }
     else if (this.btnExecute.Height > 0x1d)
     {
         this.btnExecute.Height -= 2;
     }
     else if (this.btnExecute.Height > 0x18)
     {
         this.btnExecute.Height--;
     }
     this.btnCancel.Height = this.btnExecute.Height;
     this.btnText.Height = this.btnGrids.Height = this.btnExecute.Height - 1;
     if ((IntPtr.Size == 4) && (this.btnExecute.Height > 0x1b))
     {
         Padding margin = this.cboLanguage.Margin;
         this.cboLanguage.Margin = new Padding(margin.Left, margin.Top, margin.Right, margin.Bottom - 1);
         margin = this.cboDb.Margin;
         this.cboDb.Margin = new Padding(margin.Left, margin.Top, margin.Right, margin.Bottom - 1);
     }
     if (this.btnExecute.Height > 40)
     {
         this.btnExecute.Image = ControlUtil.ResizeImage(this.btnExecute.Image, this.btnExecute.Width, this.btnExecute.Height, true);
         this.btnCancel.Image = ControlUtil.ResizeImage(this.btnCancel.Image, this.btnCancel.Width, this.btnCancel.Height, true);
         this.btnGrids.Image = ControlUtil.ResizeImage(this.btnGrids.Image, (this.btnGrids.Width * 3) / 4, (this.btnGrids.Height * 3) / 4, true);
         this.btnText.Image = ControlUtil.ResizeImage(this.btnText.Image, (this.btnText.Width * 3) / 4, (this.btnText.Height * 3) / 4, true);
     }
     this.UpdateAutocompletionMsg();
     try
     {
         this.txtError.Font = new Font("Verdana", 8.25f);
         this.txtSQL.Font = new Font("Verdana", 9.5f);
         this.btnActivateAutocompletion.Font = new Font("Verdana", 8f, FontStyle.Bold);
         this.lblOptimize.Font = new Font("Verdana", 7f, FontStyle.Bold);
     }
     catch
     {
     }
     this.txtSQL.get_Document().set_Language(DocumentManager.GetDynamicLanguage("SQL", SystemColors.Window.GetBrightness()));
     this.txtSQL.get_Document().get_Outlining().set_Mode(2);
     this.txtSQL.set_BracketHighlightingVisible(true);
     this.txtSQL.get_Document().set_ReadOnly(true);
     VisualStudio2005SyntaxEditorRenderer renderer = new VisualStudio2005SyntaxEditorRenderer();
     SimpleBorder border = new SimpleBorder();
     border.set_Style(0);
     renderer.set_Border(border);
     VisualStudio2005SyntaxEditorRenderer renderer2 = renderer;
     this.txtSQL.set_Renderer(renderer2);
     this._docMan = new DocumentManager(this._query, this);
     this.CreateEditor();
     this.PropagateOptions();
     this.UpdateEditorZoom();
     this.CreateBrowser();
     this._browserHidden = true;
     this.panBottom.BorderStyle = BorderStyle.None;
     this.tsOutput.BackColor = Color.Transparent;
     this.tsOutput.Renderer = new OutputToolsRenderer();
     this.statusStrip.BackColor = Color.Transparent;
     this.statusStrip.Padding = new Padding(this.statusStrip.Padding.Left, this.statusStrip.Padding.Top, this.statusStrip.Padding.Left, this.statusStrip.Padding.Bottom);
     this.PullData(QueryChangedEventArgs.Refresh);
     this.ToggleResultsCollapse();
     this._query.QueryCompiled += new EventHandler<QueryCompilationEventArgs>(this._query_QueryCompiled);
     this._query.PluginsReady += new EventHandler(this._query_PluginsReady);
     this._query.CustomClickCompleted += new EventHandler(this._query_CustomClickCompleted);
     this._query.QueryCompleted += new EventHandler<QueryStatusEventArgs>(this._query_QueryCompleted);
     this._query.QueryChanged += new EventHandler<QueryChangedEventArgs>(this._query_QueryChanged);
     this._query.ReadLineRequested += new EventHandler<ReadLineEventArgs>(this._query_ReadLineRequested);
     this._editor.TextChanged += new EventHandler(this._editor_TextChanged);
     this._editor.add_SelectionChanged(new SelectionEventHandler(this, (IntPtr) this._editor_SelectionChanged));
     this._editor.RepositoryDropped += new EventHandler<QueryEditor.RepositoryEventArgs>(this._editor_RepositoryDropped);
     this._schemaTree.AfterSelect += new TreeViewEventHandler(this._schemaTree_AfterSelect);
     this._docMan.CheckForRepositoryChange();
     this._refreshTimer.Tick += new EventHandler(this.RefreshTimer_Tick);
     this._clockTimer.Tick += new EventHandler(this.ClockTimer_Tick);
     this._autoSaveTimer.Tick += new EventHandler(this.AutoSaveTimer_Tick);
     if (handler2 == null)
     {
         handler2 = (sender, e) => this.ReportMainThreadPosition();
     }
     this._executionTrackingTimer.Tick += handler2;
     if (SystemColors.Window.GetBrightness() < 0.5f)
     {
         this.llDbUseCurrent.ForeColor = SystemColors.HotTrack;
     }
     this.ExtendOutputSplitter();
     if (handler3 == null)
     {
         handler3 = (sender, e) => this.UpdateErrorHeight();
     }
     this.panError.SizeChanged += handler3;
     this.statusStrip.Parent = null;
     base.Controls.Add(this.statusStrip);
     this.statusStrip.SendToBack();
     if (handler4 == null)
     {
         handler4 = (sender, e) => this.RequestWinManagerRelocation();
     }
     EventHandler handler6 = handler4;
     this.panOutput.Resize += handler6;
     for (Control control = this.panOutput; control != null; control = control.Parent)
     {
         control.Move += handler6;
     }
     this._query.PluginWindowManager = this._pluginWinManager;
     this.queryProgressBar.Margin = new Padding(3, 3, 0, 1);
     this.tsOutput.Padding = new Padding(0, 0, 0, 2);
     this.splitContainer.SplitterWidth--;
     if (handler5 == null)
     {
         handler5 = delegate (object sender, SplitterCancelEventArgs e) {
             if (Control.MouseButtons == MouseButtons.Left)
             {
                 MainForm.Instance.IsSplitting = true;
             }
             if ((this.panOutput.BackColor == MainForm.Instance.TransparencyKey) && (this.panOutput.BackColor != Program.LightTransparencyKey))
             {
                 this.panOutput.BackColor = MainForm.Instance.TransparencyKey = Program.LightTransparencyKey;
             }
         };
     }
     this.splitContainer.SplitterMoving += handler5;
     this.panOutput.BorderStyle = BorderStyle.None;
     this.panOutput.BorderColor = Color.FromArgb(160, 160, 160);
     this.lblSyncDb.Cursor = Cursors.Hand;
     this.toolTip.ShowAlways = true;
     this.EnableControls();
     this.panBottom.Layout += new LayoutEventHandler(this.panBottom_Layout);
 }
		/// <summary>
		/// Initializes a new instance of the <see cref="HqlBasedQuery"/> class.
		/// </summary>
		/// <param name="targetType">Type of the target.</param>
		/// <param name="queryLanguage">The query language.</param>
		/// <param name="query">The query.</param>
		/// <param name="positionalParameters">The positional parameters.</param>
		public HqlBasedQuery(Type targetType, QueryLanguage queryLanguage, string query, params object[] positionalParameters)
			: this(targetType, queryLanguage, query)
		{
			if (positionalParameters != null && positionalParameters.Length > 0)
			{
				int i = 0;
				foreach (object value in positionalParameters)
				{
					ValueAndTypeTuple valueAndTypeTuple = ValueAndTypeTuple.Wrap(value);
					AddModifier(new QueryParameter(i++, valueAndTypeTuple.Value, valueAndTypeTuple.Type));
				}
			}
		}
 internal void Run(bool compileOnly)
 {
     if (!base.IsDisposed && !this.QueryRunning)
     {
         this._gotQueryCompletionMessage = false;
         this._compileOnly = compileOnly;
         this._memoryAtStart = GC.GetTotalMemory(false);
         this._lastExecutionProgress = 5;
         bool? nullable = null;
         this._lastAutoScrollResultsFromQuery = nullable;
         this._autoScrollResultsFromQuery = this._lastAutoScrollResultsFromQuery = nullable;
         this._pendingResultsShow = true;
         this._modifiedWhenRunning = false;
         this._uberCancelMessage = false;
         this._pendingSqlTranslation = null;
         this.lblMiscStatus.Text = "";
         this._queryCount++;
         this._outputInfoMessage = null;
         this.ClearExecutionTrackingIndicators();
         this._executionTrackingTimer.Stop();
         this.ClearExecutionTrackingIndicators();
         this._firstExecutionTrack = true;
         this._lastExecutionTrackCost2 = 0;
         this._lastExecutionTrackCost1 = 0;
         this._lastExecutionLine = -1;
         this._lastTrackInfo = null;
         this._executingQueryOptimized = UserOptionsLive.Instance.OptimizeQueries;
         this._executingQueryLanguage = this._query.QueryKind;
         this._gotPluginsReadyMessage = false;
         this.KillIEComExceptionTimer();
         this.ClearQueryHighlight();
         this.panOutput.BackColor = Color.White;
         this.panOutput.Update();
         this._docMan.MainErrorLayer.Clear();
         this._docMan.WarningsLayer.Clear();
         this._docMan.StackTraceLayer.Clear();
         this._docMan.ExecutedSelectionLayer.Clear();
         this._editor.set_IndicatorMarginVisible(false);
         this._editor.get_Document().get_LineIndicators().Clear();
         string str = this._editor.get_SelectedView().get_SelectedText();
         if (this.CheckAndPromptQueryDriver())
         {
             if (this._query != null)
             {
                 this._query.SuppressErrorsOnExistingClient();
             }
             this.ResetPluginManager(false);
             string querySelection = ((str.Trim().Length <= 1) || compileOnly) ? null : this._editor.get_SelectedView().get_SelectedText();
             QueryCompilationEventArgs lastCompiler = (this._query.RequiresRecompilation || (this._lastRanSourceSelection != querySelection)) ? null : this._lastCompilation;
             this._lastRanSourceSelection = querySelection;
             if (querySelection != null)
             {
                 this._docMan.ExecutedSelectionLayer.Add(new GrayCodeSpanIndicator(), new TextRange(0, this._editor.get_SelectedView().get_Selection().get_FirstOffset()), false);
                 this._docMan.ExecutedSelectionLayer.Add(new GrayCodeSpanIndicator(), new TextRange(this._editor.get_SelectedView().get_Selection().get_LastOffset(), this._editor.get_Document().get_Length()), false);
                 this._querySelectionStartRow = this._editor.get_SelectedView().get_Selection().get_FirstDocumentPosition().get_Line();
                 this._querySelectionStartCol = this._editor.get_SelectedView().get_Selection().get_FirstDocumentPosition().get_Character();
                 this._query.Run(querySelection, compileOnly, lastCompiler, this._pluginWinManager);
             }
             else
             {
                 this._querySelectionStartCol = 0;
                 this._querySelectionStartRow = 0;
                 this._query.Run(null, compileOnly, lastCompiler, this._pluginWinManager);
             }
             this.queryProgressBar.Style = ProgressBarStyle.Marquee;
             this.lblUberCancel.Visible = false;
             this.panError.Hide();
             this.btnResults.Text = this._query.ToDataGrids ? "&Output" : "&Results";
             this.btnSql.Text = ((this._query.Repository == null) || (!(this._query.Repository.DriverLoader.InternalID == "AstoriaAuto") && !(this._query.Repository.DriverLoader.InternalID == "DallasAuto"))) ? "&SQL" : "Reque&st Log";
             if (!compileOnly)
             {
                 this.SetDataContent("");
                 this.SetLambdaContent("");
                 this.SetSqlContent("");
                 this._browserHidden = true;
             }
             this.EnableControls();
             this.lblExecTime.Visible = false;
             this.lblElapsed.Text = "";
             this.lblElapsed.Visible = true;
             this._clockTimer.Start();
             this._refreshTimer.Interval = 200;
             this._refreshTimer.Start();
             this.UpdateAutocompletionMsg();
             this._editor.Focus();
         }
     }
 }
 private SingletonProjectionRewriter(QueryLanguage language)
 {
     this.language = language;
 }
 private int QueryLanguageToIndex(QueryLanguage language)
 {
     if (this._query.IsMyExtensions)
     {
         return 0;
     }
     int num2 = (int) language;
     if (language >= QueryLanguage.SQL)
     {
         num2 -= 2;
     }
     else if ((language == QueryLanguage.FSharpExpression) || (language == QueryLanguage.FSharpProgram))
     {
         num2 += 2;
     }
     return num2;
 }
 internal void PullData(QueryChangedEventArgs changeInfo)
 {
     this.CheckIsMyExtensions();
     if (this._suppressPullCount <= 0)
     {
         bool flag = false;
         bool flag2 = false;
         using (this.SuppressPull())
         {
             if (changeInfo.SourceChanged && (this._editor.Text != this._query.Source))
             {
                 this._editor.Text = this._query.Source;
                 this._editor.set_IndicatorMarginVisible(false);
                 this._editor.get_Document().get_LineIndicators().Clear();
             }
             this._editor.IsOutliningEnabled = (this._query.QueryKind == QueryLanguage.Program) || (this._query.QueryKind == QueryLanguage.VBProgram);
             this.btnPin.Checked = this._query.Pinned;
             this.cboLanguage.SelectedIndex = this.QueryLanguageToIndex(this._query.QueryKind);
             this.btnGrids.Checked = this._query.ToDataGrids;
             this.btnText.Checked = !this._query.ToDataGrids;
             bool flag3 = false;
             if (changeInfo.ReferencesChanged && this._query.IsMyExtensions)
             {
                 MyExtensions.UpdateAdditionalRefs(this._query);
                 this._docMan.ResetSharedReferences(MyExtensions.AdditionalRefs);
             }
             if (((this._lastQueryKind != this._query.QueryKind) || changeInfo.ReferencesChanged) || changeInfo.NamespacesChanged)
             {
                 flag2 = (this._lastQueryKind != this._query.QueryKind) && (this._lastQueryKind >= QueryLanguage.FSharpExpression);
                 this._lastQueryKind = this._query.QueryKind;
                 this._docMan.ConfigureLanguage();
                 this._docMan.ConfigureResolver();
                 flag3 = true;
             }
             this.lblSyncDb.Visible = this._query.Repository != null;
             if (changeInfo.DbChanged)
             {
                 this.UpdateRepositoryItems(false);
                 this.UpdateFocusedRepository();
             }
             if ((!flag3 && !this._docMan.CheckForRepositoryChange()) && (flag || flag2))
             {
                 this._docMan.ConfigureResolver();
             }
         }
         this.UpdateOutputVisibility();
         if (base.Parent != null)
         {
             this._schemaTree.UpdateSqlMode(this._query);
         }
     }
 }
 private bool IsQueryLanguageTrackable(QueryLanguage language)
 {
     return ((((language == QueryLanguage.Statements) || (language == QueryLanguage.Program)) || (language == QueryLanguage.VBStatements)) || (language == QueryLanguage.VBProgram));
 }
Exemple #49
0
 private static string GetSourceExtension(QueryLanguage kind)
 {
     switch (kind)
     {
         case QueryLanguage.Expression:
         case QueryLanguage.Statements:
         case QueryLanguage.Program:
             return ".cs";
         case QueryLanguage.VBExpression:
         case QueryLanguage.VBStatements:
         case QueryLanguage.VBProgram:
             return ".vb";
         case QueryLanguage.FSharpExpression:
         case QueryLanguage.FSharpProgram:
             return ".fsx";
         case QueryLanguage.SQL:
         case QueryLanguage.ESQL:
             return ".sql";
         default:
             return ".txt";
     }
 }
 public static Expression Rewrite(QueryLanguage language, Expression expression)
 {
     return new SingletonProjectionRewriter(language).Visit(expression);
 }
Exemple #51
0
 public QueryControl AddQueryPage(bool noPin, bool copyProps, string initialText, QueryLanguage? forcedQueryKind, string name, bool noTemplateText, bool focusEllipses, bool intoGrids)
 {
     RunnableQuery q = (this.NextCacheQueryControl == null) ? new RunnableQuery() : this.NextCacheQueryControl.Query;
     q.ReadDefaultSettings();
     q.Source = initialText;
     Repository repository = ((this.CurrentQuery == null) || !copyProps) ? this.schemaTree.GetCurrentRepository(true) : this.CurrentQuery.Repository;
     if (repository != null)
     {
         q.Repository = repository;
     }
     if (forcedQueryKind.HasValue)
     {
         q.QueryKind = forcedQueryKind.Value;
     }
     if ((this.CurrentQuery != null) && copyProps)
     {
         q.AdditionalNamespaces = this.CurrentQuery.AdditionalNamespaces;
         q.AdditionalReferences = this.CurrentQuery.AdditionalReferences;
         q.AdditionalGACReferences = this.CurrentQuery.AdditionalGACReferences;
         if (!forcedQueryKind.HasValue)
         {
             q.QueryKind = this.CurrentQuery.QueryKind;
         }
         q.IncludePredicateBuilder = this.CurrentQuery.IncludePredicateBuilder;
         q.ToDataGrids = this.CurrentQuery.ToDataGrids;
     }
     else
     {
         QueryLanguage? nullable;
         if ((!forcedQueryKind.HasValue && UserOptions.Instance.DefaultQueryLanguage.HasValue) && ((((QueryLanguage) (nullable = UserOptions.Instance.DefaultQueryLanguage).GetValueOrDefault()) != QueryLanguage.Expression) || !nullable.HasValue))
         {
             q.QueryKind = UserOptions.Instance.DefaultQueryLanguage.Value;
         }
         else if (!(forcedQueryKind.HasValue || (this.CurrentQuery == null)) && this.CurrentQuery.QueryKind.ToString().StartsWith("VB", StringComparison.Ordinal))
         {
             q.QueryKind = QueryLanguage.VBExpression;
         }
     }
     if (string.IsNullOrEmpty(name))
     {
         q.Name = "Query " + this._untitledCount++;
     }
     else
     {
         q.Name = name;
     }
     if (noPin)
     {
         q.Pinned = false;
     }
     if (intoGrids)
     {
         q.ToDataGrids = true;
     }
     QueryControl control = this.AddQueryPage(q, focusEllipses, copyProps);
     if (!noTemplateText)
     {
         control.CheckToFromProgramLanguage(QueryLanguage.Expression, q.QueryKind, false, q.Repository != null);
     }
     q.IsModified = false;
     return control;
 }
 public NewQueryArgs(string queryText, QueryLanguage? language) : this(queryText, language, false)
 {
 }
 public static string GetDataInsertionString(QueryLanguage ql)
 {
     return "INSERT INTO [" + ql.ToString() + "] (Book, Chapter, Verse, Word) VALUES (N'@Book', @Chapter, @Verse, N'@Word')";
 }
 internal void CheckToFromProgramLanguage(QueryLanguage oldLanguage, QueryLanguage newLanguage, bool oldDC, bool newDC)
 {
     string str2;
     bool flag = (oldLanguage == QueryLanguage.FSharpProgram) && oldDC;
     bool flag2 = (newLanguage == QueryLanguage.FSharpProgram) && newDC;
     string str = UserOptions.Instance.ConvertTabsToSpaces ? "".PadRight(UserOptions.Instance.TabSizeActual) : "\t";
     if ((oldLanguage == QueryLanguage.Program) && (newLanguage != QueryLanguage.Program))
     {
         if (this._editor.Text.StartsWith("void Main", StringComparison.Ordinal) && this._editor.Text.TrimEnd(new char[0]).EndsWith("// Define other methods and classes here", StringComparison.Ordinal))
         {
             str2 = Regex.Replace(Regex.Replace(this._editor.Text, @"^void Main\s*\(\s*\)\s*{\s*", ""), @"\s*}\s*// Define other methods and classes here\s*$", "").Replace("\n" + str, "\n");
             this._editor.Text = str2;
         }
     }
     else if ((oldLanguage == QueryLanguage.VBProgram) && (newLanguage != QueryLanguage.VBProgram))
     {
         if (this._editor.Text.StartsWith("Sub Main", StringComparison.OrdinalIgnoreCase) && this._editor.Text.TrimEnd(new char[0]).EndsWith("' Define other methods and classes here", StringComparison.OrdinalIgnoreCase))
         {
             str2 = Regex.Replace(Regex.Replace(this._editor.Text, @"^Sub Main\s*", "", RegexOptions.IgnoreCase), @"\s*End Sub\s*' Define other methods and classes here\s*$", "", RegexOptions.IgnoreCase).Replace("\n" + str, "\n");
             this._editor.Text = str2;
         }
     }
     else if (!(!flag || flag2) && this._editor.Text.StartsWith("let dc = new TypedDataContext()", StringComparison.Ordinal))
     {
         this._editor.Text = this._editor.Text.Substring("let dc = new TypedDataContext()".Length).TrimStart(new char[0]);
     }
     if ((oldLanguage != QueryLanguage.Program) && (newLanguage == QueryLanguage.Program))
     {
         if (!((this._editor.Text.Contains("void Main") || this._editor.Text.ToUpperInvariant().Contains("SUB MAIN")) || this._editor.Text.Contains("Task Main")))
         {
             this._editor.Text = "void Main()\n{\n" + str + this._query.Source.Replace("\n", "\n" + str) + "\n}\n\n// Define other methods and classes here\n";
             this._editor.get_SelectedView().get_Selection().set_TextRange(new TextRange(14 + str.Length));
         }
     }
     else if ((oldLanguage != QueryLanguage.VBProgram) && (newLanguage == QueryLanguage.VBProgram))
     {
         if (!(this._editor.Text.ToUpperInvariant().Contains("SUB MAIN") || this._editor.Text.Contains("void Main")))
         {
             this._editor.Text = "Sub Main\n" + str + this._query.Source.Replace("\n", "\n" + str) + "\nEnd Sub\n\n' Define other methods and classes here\n";
             this._editor.get_SelectedView().get_Selection().set_TextRange(new TextRange(9 + str.Length));
         }
     }
     else if (!(flag || !flag2) && !this._editor.Text.Contains("let dc = new TypedDataContext()"))
     {
         this._editor.Text = "let dc = new TypedDataContext()\r\n\r\n" + this._query.Source;
         this._editor.get_SelectedView().get_Selection().set_TextRange(new TextRange("let dc = new TypedDataContext()".Length + 2));
     }
 }
		/// <summary>
		/// Initializes a new instance of the <see cref="HqlBasedQuery"/> class.
		/// </summary>
		/// <param name="targetType">Type of the target.</param>
		/// <param name="queryLanguage">The query language.</param>
		/// <param name="query">The query.</param>
		public HqlBasedQuery(Type targetType, QueryLanguage queryLanguage, string query)
			: base(targetType)
		{
			this.query = query;
			this.queryLanguage = queryLanguage;
		}
Exemple #56
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ScalarQuery"/> class.
 /// </summary>
 /// <param name="targetType">Type of the target.</param>
 /// <param name="queryLanguage">The query language.</param>
 /// <param name="query">The query.</param>
 /// <param name="positionalParameters">The positional parameters.</param>
 public ScalarQuery(Type targetType, QueryLanguage queryLanguage, string query, params Object[] positionalParameters)
     : base(targetType, queryLanguage, query, positionalParameters)
 {
 }
Exemple #57
0
 public void ExecuteSqlQuery(QueryLanguage language, LINQPad.Repository repository, string query, string[] refs, Client client, LINQPad.UI.PluginWindowManager pluginWinManager)
 {
     QueryRunner runner;
     this.IsClrQuery = false;
     Util.Progress = null;
     this._repository = repository;
     this._sqlQuery = query;
     this._client = client;
     this._additionalRefs = refs;
     CurrentQueryAdditionalRefs = this._additionalRefs;
     this.PluginWindowManager = pluginWinManager;
     if (language == QueryLanguage.ESQL)
     {
         runner = new ESqlQueryRunner(this, query);
     }
     else
     {
         runner = new SqlQueryRunner(this, query);
     }
     Thread thread = new Thread(() => this.StartQuery(runner)) {
         Name = ((language == QueryLanguage.ESQL) ? "E" : "") + "SQL Query Runner",
         IsBackground = true
     };
     this._worker = thread;
     this._worker.SetApartmentState(ApartmentState.STA);
     this._worker.Start();
 }
Exemple #58
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ScalarQuery"/> class.
 /// </summary>
 /// <param name="targetType">Type of the target.</param>
 /// <param name="queryLanguage">The query language.</param>
 /// <param name="query">The query.</param>
 public ScalarQuery(Type targetType, QueryLanguage queryLanguage, string query)
     : base(targetType, queryLanguage, query)
 {
 }
Exemple #59
0
		/// <summary>
		/// Creates a new <c>SimpleQuery</c>.
		/// </summary>
		public SimpleQuery(Type targetType, Type returnType, QueryLanguage queryLanguage, string query, params object[] parameters)
			: base(targetType, queryLanguage, query, parameters)
		{
			this.returnType = returnType;
		}
 public NewQueryArgs(string queryText, QueryLanguage? language, bool runNow)
 {
     this._queryText = queryText;
     this.Language = language;
     this.RunNow = runNow;
 }