Esempio n. 1
0
            public Header(System.Data.SQLite.SQLiteConnection connection)
            {
                System.Collections.Hashtable hash = null;

                using (var sqlcommand = connection.CreateCommand())
                {

                    sqlcommand.CommandText = clientBuildCommand;
                    using (var reader = sqlcommand.ExecuteReader())
                    {
                        var total = reader.RecordsAffected;
                        hash = new System.Collections.Hashtable(total);
                        while (reader.Read())
                        {
                            hash[reader.GetString(0)] = reader.GetValue(1);
                        }
                        reader.Close();
                    }


                }

                ClientBuild = (ClientBuild)int.Parse((string)hash["clientBuild"]);
                AccountName = (string)hash["accountName"];
                RealmName = (string)hash["realmName"];
                RealmServer = (string)hash["realmServer"];


                //connection.Close();
            }
Esempio n. 2
0
		public static void Main (string[] args)
		{


			MySqlConnection mySqlConnection= new MySqlConnection("" +
			                                                     "Server= localhost;Database=dbprueba;User ID = root; Password= sistemas"");

mySqlConnection.Open();	

Console.WriteLine ("Hello World!");

MySqlCommand mySqlCommand= mySqlConnection.CreateCommand();
mySqlCommand.CommandText= string.Format("insert into categoria(nombre)values ('{0}')", DateTime.Now);
mySqlCommand.ExecuteNonQuery;

mySqlCommand.CommandText= "select * from categoria";

MySqlDataReader mySqlDataReader= mySqlCommand.ExecuteReader();
Console.WriteLine("FieldCount={0}", mySqlDataReader.FieldCount);
for(int index=0; index < mySqlDataReader.FieldCount; index++)
Console.WriteLine("colum{0}={1}", indexer, mySqlDataReader.getName(indexer));

while(mySqlDataReader.Read()){
object id= mySqlDataReader["nombre"];
Console.WriteLine("id={0} nombre={1}", id , nombre);

mySqlDataReader.Close();


mySqlConnection.Close();
}
}
 protected override void DoWork(System.Data.SqlClient.SqlConnection connection)
 {
     string query = SqlQueries.SetSingleUser + Environment.NewLine + SqlQueries.DetachDatabase;
       query = string.Format(query, Database);
       SqlCommand command = connection.CreateCommand();
       command.CommandText = query;
       command.ExecuteNonQuery();
 }
Esempio n. 4
0
        /// <summary>
        /// 构造函数,接收一个SqlServer数据库连接对象SqlConnection
        /// </summary>
        public SqlDbOperHandler(System.Data.SqlClient.SqlConnection _conn)
        {
            conn = _conn;
            dbType = DatabaseType.SqlServer;

            conn.Open();
            cmd = conn.CreateCommand();
            da = new System.Data.SqlClient.SqlDataAdapter();
        }
Esempio n. 5
0
 private void UseDb(System.Data.SqlClient.SqlConnection conn, string dbName)
 {
     using (var cmd = conn.CreateCommand())
     {
         cmd.CommandText = "USE [" + dbName + "]";
         cmd.CommandType = CommandType.Text;
         cmd.ExecuteNonQuery();
     }
 }
Esempio n. 6
0
 private void DetachDb(System.Data.SqlClient.SqlConnection conn, string dbName)
 {
     using (var cmd = conn.CreateCommand())
     {
         cmd.CommandText = "sp_detach_db";
         cmd.CommandType = CommandType.StoredProcedure;
         cmd.Parameters.AddWithValue("@dbname", dbName);
         cmd.ExecuteNonQuery();
     }
 }
 protected override bool isServerUp(System.Data.IDbConnection cnx)
 {
     if (base.isServerUp(cnx))
     {
         using (var cmd = cnx.CreateCommand())
         {
             cmd.CommandText = "SELECT now()"; // execute dumb command
             cmd.ExecuteScalar();
         }
     }
     return true;
 }
Esempio n. 8
0
        public T LoadByCode(string code, DBColumn column, DBLoadParam param, DBTransaction transaction = null)
        {
            var row = SelectOne(column, code);

            if (row == null && (param & DBLoadParam.Load) == DBLoadParam.Load)//&& !IsSynchronized
            {
                var command = System.CreateCommand(Schema.Connection, CreateQuery($"where a.{column.Name}={Schema.System.ParameterPrefix}{column.Name}", "a", Columns));
                System.CreateParameter(command, Schema.System.ParameterPrefix + column.Name, code, column);
                row = Load(command, param, transaction).FirstOrDefault();
            }
            return(row);
        }
		public System.Data.OleDb.OleDbCommand CreateStatement(System.Data.OleDb.OleDbConnection connection) {
		    System.Data.OleDb.OleDbCommand command = connection.CreateCommand();
		    System.Data.OleDb.OleDbTransaction transaction;
		    if (this[connection] != null) {
			ConnectionProperties Properties = ((ConnectionProperties) this[connection]);
			transaction = Properties.Transaction;
			command.Transaction = transaction;
		    } else {
			ConnectionProperties TempProp = new ConnectionProperties();
			TempProp.AutoCommit=false;
			TempProp.TransactionLevel = 0;
			command.Transaction = TempProp.Transaction;
			Add(connection, TempProp);
		    }
		    return command;
		}
Esempio n. 10
0
            public static IEnumerable<IExistingFile> GetExistingFilesWithBlocks(System.Data.IDbConnection connection, string tablename)
            {
                using(var cmd = connection.CreateCommand())
                {
                    cmd.CommandText = string.Format(@"SELECT ""{0}"".""TargetPath"", ""Blockset"".""FullHash"", ""{0}"".""ID"", ""Blockset"".""Length"", ""Block"".""Hash"", ""BlocksetEntry"".""Index"", ""Block"".""Size"" FROM ""{0}"", ""Blockset"", ""BlocksetEntry"", ""Block"" WHERE ""{0}"".""BlocksetID"" = ""Blockset"".""ID"" AND ""BlocksetEntry"".""BlocksetID"" = ""{0}"".""BlocksetID"" AND ""BlocksetEntry"".""BlockID"" = ""Block"".""ID"" ORDER BY ""{0}"".""TargetPath"", ""BlocksetEntry"".""Index""", tablename);
                    using(var rd = cmd.ExecuteReader())
                        if (rd.Read())
                        {
                            var more = true;
                            while(more)
                            {
                                var f = new ExistingFile(rd);
                                string current = f.TargetPath;
                                yield return f;

                                more = f.HasMore;
                                while (more && current == f.TargetPath)
                                    more = rd.Read();
                            }
                        }
                }
            }
Esempio n. 11
0
 public BlockMarker(System.Data.IDbConnection connection, string blocktablename, string filetablename)
 {
     m_insertblockCommand = connection.CreateCommand();
     m_resetfileCommand  = connection.CreateCommand();
     m_updateAsRestoredCommand = connection.CreateCommand();
     m_statUpdateCommand = connection.CreateCommand();
     
     m_insertblockCommand.Transaction = connection.BeginTransaction();
     m_resetfileCommand.Transaction = m_insertblockCommand.Transaction;
     m_updateAsRestoredCommand.Transaction = m_insertblockCommand.Transaction;
     m_statUpdateCommand.Transaction = m_insertblockCommand.Transaction;
     
     m_blocktablename = blocktablename;
     m_updateTable = "UpdatedBlocks-" + Library.Utility.Utility.ByteArrayAsHexString(Guid.NewGuid().ToByteArray());
     
     m_insertblockCommand.ExecuteNonQuery(string.Format(@"CREATE TEMPORARY TABLE ""{0}"" (""FileID"" INTEGER NOT NULL, ""Index"" INTEGER NOT NULL, ""Hash"" TEXT NOT NULL, ""Size"" INTEGER NOT NULL)", m_updateTable));
     m_insertblockCommand.CommandText = string.Format(@"INSERT INTO ""{0}"" (""FileID"", ""Index"", ""Hash"", ""Size"") VALUES (?, ?, ?, ?) ", m_updateTable);
     m_insertblockCommand.AddParameters(4);
                     
     m_resetfileCommand.CommandText = string.Format(@"DELETE FROM ""{0}"" WHERE ""FileID"" = ?", m_updateTable);
     m_resetfileCommand.AddParameters(1);
     
     m_updateAsRestoredCommand.CommandText = string.Format(@"INSERT INTO ""{0}"" (""FileID"", ""Index"", ""Hash"", ""Size"") SELECT ""FileID"", ""Index"", ""Hash"", ""Size"" FROM ""{1}"" WHERE ""{1}"".""FileID"" = ?", m_updateTable, m_blocktablename);
     m_updateAsRestoredCommand.AddParameters(1);
     
     m_statUpdateCommand.CommandText = string.Format(@"SELECT COUNT(DISTINCT ""FileID""), SUM(""Size"") FROM ""{0}"" WHERE ""Restored"" = 1 OR ""ID"" IN (SELECT ""{0}"".""ID"" FROM ""{0}"", ""{1}"" WHERE ""{0}"".""FileID"" = ""{1}"".""FileID"" AND ""{0}"".""Index"" = ""{1}"".""Index"" AND ""{0}"".""Hash"" = ""{1}"".""Hash"" AND ""{0}"".""Size"" = ""{1}"".""Size"" )", m_blocktablename, m_updateTable);
 }
 private void SetNullOn(System.Data.OleDb.OleDbConnection connection)
 {
     //Set this so that FoxPro doesn't try to insert null values in empty columns
     System.Data.OleDb.OleDbCommand dbCmdNull = connection.CreateCommand();
     dbCmdNull.CommandText = "SET NULL ON";
     dbCmdNull.ExecuteNonQuery();
 }
Esempio n. 13
0
        private static CommandProcessorBase AddCommand(PipelineProcessor pipe, CommandParameterInternal[] commandElements, CommandBaseAst commandBaseAst, CommandRedirection[] redirections, System.Management.Automation.ExecutionContext context)
        {
            object parameterText;
            IScriptExtent parameterExtent;
            CommandProcessorBase base2;
            InternalCommand command;
            string str3;
            HelpCategory category;
            CommandAst ast = commandBaseAst as CommandAst;
            TokenKind kind = (ast != null) ? ast.InvocationOperator : TokenKind.Unknown;
            bool dotSource = kind == TokenKind.Dot;
            SessionStateInternal sessionState = null;
            int index = 0;
            PSModuleInfo info = PSObject.Base(commandElements[0].ArgumentValue) as PSModuleInfo;
            if (info != null)
            {
                if ((info.ModuleType == ModuleType.Binary) && (info.SessionState == null))
                {
                    throw InterpreterError.NewInterpreterException(null, typeof(RuntimeException), null, "CantInvokeInBinaryModule", ParserStrings.CantInvokeInBinaryModule, new object[] { info.Name });
                }
                if (info.SessionState == null)
                {
                    throw InterpreterError.NewInterpreterException(null, typeof(RuntimeException), null, "CantInvokeInNonImportedModule", ParserStrings.CantInvokeInNonImportedModule, new object[] { info.Name });
                }
                sessionState = info.SessionState.Internal;
                index++;
            }
            CommandParameterInternal internal3 = commandElements[index];
            if (internal3.ParameterNameSpecified)
            {
                parameterText = internal3.ParameterText;
                parameterExtent = internal3.ParameterExtent;
                if (!internal3.ArgumentSpecified)
                {
                }
            }
            else
            {
                parameterText = PSObject.Base(internal3.ArgumentValue);
                parameterExtent = internal3.ArgumentExtent;
            }
            string str = dotSource ? "." : ((kind == TokenKind.Ampersand) ? "&" : null);
            ScriptBlock scriptblock = parameterText as ScriptBlock;
            if (scriptblock != null)
            {
                base2 = CommandDiscovery.CreateCommandProcessorForScript(scriptblock, context, !dotSource, sessionState);
            }
            else
            {
                CommandInfo commandInfo = parameterText as CommandInfo;
                if (commandInfo != null)
                {
                    base2 = context.CommandDiscovery.LookupCommandProcessor(commandInfo, context.EngineSessionState.CurrentScope.ScopeOrigin, new bool?(!dotSource), sessionState);
                }
                else
                {
                    string str2 = (parameterText as string) ?? PSObject.ToStringParser(context, parameterText);
                    str = str ?? str2;
                    if (string.IsNullOrEmpty(str2))
                    {
                        throw InterpreterError.NewInterpreterException(parameterText, typeof(RuntimeException), parameterExtent, "BadExpression", ParserStrings.BadExpression, new object[] { dotSource ? "." : "&" });
                    }
                    try
                    {
                        if (sessionState != null)
                        {
                            SessionStateInternal engineSessionState = context.EngineSessionState;
                            try
                            {
                                context.EngineSessionState = sessionState;
                                base2 = context.CreateCommand(str2, dotSource);
                                goto Label_025D;
                            }
                            finally
                            {
                                context.EngineSessionState = engineSessionState;
                            }
                        }
                        base2 = context.CreateCommand(str2, dotSource);
                    }

                    catch (RuntimeException exception)
                    {
                        if (exception.ErrorRecord.InvocationInfo == null)
                        {
                            InvocationInfo invocationInfo = new InvocationInfo(null, parameterExtent, context) {
                                InvocationName = str
                            };
                            exception.ErrorRecord.SetInvocationInfo(invocationInfo);
                        }
                        throw;
                    }
                }
            }
        Label_025D:
            command = base2.Command;
            base2.UseLocalScope = !dotSource && ((command is ScriptCommand) || (command is PSScriptCmdlet));
            bool flag2 = base2 is NativeCommandProcessor;
            for (int i = index + 1; i < commandElements.Length; i++)
            {
                CommandParameterInternal parameter = commandElements[i];
                if ((!parameter.ParameterNameSpecified || !parameter.ParameterName.Equals("-", StringComparison.OrdinalIgnoreCase)) || flag2)
                {
                    if (parameter.ArgumentSplatted)
                    {
                        foreach (CommandParameterInternal internal6 in Splat(parameter.ArgumentValue, parameter.ArgumentExtent))
                        {
                            base2.AddParameter(internal6);
                        }
                    }
                    else
                    {
                        base2.AddParameter(parameter);
                    }
                }
            }
            if (base2.IsHelpRequested(out str3, out category))
            {
                base2 = CommandProcessorBase.CreateGetHelpCommandProcessor(context, str3, category);
            }
            base2.Command.InvocationExtent = commandBaseAst.Extent;
            base2.Command.MyInvocation.ScriptPosition = commandBaseAst.Extent;
            base2.Command.MyInvocation.InvocationName = str;
            pipe.Add(base2);
            bool flag3 = false;
            bool flag4 = false;
            bool flag5 = false;
            bool flag6 = false;
            if (redirections != null)
            {
                foreach (CommandRedirection redirection in redirections)
                {
                    redirection.Bind(pipe, base2, context);
                    switch (redirection.FromStream)
                    {
                        case RedirectionStream.All:
                            flag3 = true;
                            flag4 = true;
                            flag5 = true;
                            flag6 = true;
                            break;

                        case RedirectionStream.Error:
                            flag3 = true;
                            break;

                        case RedirectionStream.Warning:
                            flag4 = true;
                            break;

                        case RedirectionStream.Verbose:
                            flag5 = true;
                            break;

                        case RedirectionStream.Debug:
                            flag6 = true;
                            break;
                    }
                }
            }
            if (!flag3)
            {
                if (context.ShellFunctionErrorOutputPipe != null)
                {
                    base2.CommandRuntime.ErrorOutputPipe = context.ShellFunctionErrorOutputPipe;
                }
                else
                {
                    base2.CommandRuntime.ErrorOutputPipe.ExternalWriter = context.ExternalErrorOutput;
                }
            }
            if (!flag4 && (context.ExpressionWarningOutputPipe != null))
            {
                base2.CommandRuntime.WarningOutputPipe = context.ExpressionWarningOutputPipe;
                flag4 = true;
            }
            if (!flag5 && (context.ExpressionVerboseOutputPipe != null))
            {
                base2.CommandRuntime.VerboseOutputPipe = context.ExpressionVerboseOutputPipe;
                flag5 = true;
            }
            if (!flag6 && (context.ExpressionDebugOutputPipe != null))
            {
                base2.CommandRuntime.DebugOutputPipe = context.ExpressionDebugOutputPipe;
                flag6 = true;
            }
            if ((context.CurrentCommandProcessor != null) && (context.CurrentCommandProcessor.CommandRuntime != null))
            {
                if (!flag4 && (context.CurrentCommandProcessor.CommandRuntime.WarningOutputPipe != null))
                {
                    base2.CommandRuntime.WarningOutputPipe = context.CurrentCommandProcessor.CommandRuntime.WarningOutputPipe;
                }
                if (!flag5 && (context.CurrentCommandProcessor.CommandRuntime.VerboseOutputPipe != null))
                {
                    base2.CommandRuntime.VerboseOutputPipe = context.CurrentCommandProcessor.CommandRuntime.VerboseOutputPipe;
                }
                if (!flag6 && (context.CurrentCommandProcessor.CommandRuntime.DebugOutputPipe != null))
                {
                    base2.CommandRuntime.DebugOutputPipe = context.CurrentCommandProcessor.CommandRuntime.DebugOutputPipe;
                }
            }
            return base2;
        }
Esempio n. 14
0
 public IDbCommand CreateCommand(string query = null, CommandType commandType = CommandType.Text)
 {
     return(System.CreateCommand(this, query, commandType));
 }
Esempio n. 15
0
        /// <summary>
        /// Helper method with logic to handle opening a database in possibly encrypted format
        /// </summary>
        /// <param name="con">The SQLite connection object</param>
        internal static void OpenDatabase(System.Data.IDbConnection con)
        {
            bool noEncryption = !Program.UseDatabaseEncryption;
            string password = Environment.GetEnvironmentVariable(DB_KEY_ENV_NAME);

            System.Reflection.MethodInfo setPwdMethod = con.GetType().GetMethod("SetPassword", new Type[] { typeof(string) });
            string attemptedPassword;

            if (noEncryption || string.IsNullOrEmpty(password))
                attemptedPassword = null; //No encryption specified, attempt to open without
            else
                attemptedPassword = password; //Encryption specified, attempt to open with

            if (setPwdMethod != null)
                setPwdMethod.Invoke(con, new object[] { attemptedPassword });

            try
            {
                //Attempt to open in preferred state
                con.Open();

                // Do a dummy query to make sure we have a working db
                using (var cmd = con.CreateCommand())
                {
                    cmd.CommandText = "SELECT COUNT(*) FROM SQLITE_MASTER";
                    cmd.ExecuteScalar();
                }
            }
            catch
            {
                try
                {
                    //We can't try anything else without a password
                    if (string.IsNullOrEmpty(password))
                        throw;

                    //Open failed, now try the reverse
                    if (attemptedPassword == null)
                        attemptedPassword = password;
                    else
                        attemptedPassword = null;

                    con.Close();
                    setPwdMethod.Invoke(con, new object[] { attemptedPassword });
                    con.Open();

                    // Do a dummy query to make sure we have a working db
                    using (var cmd = con.CreateCommand())
                    {
                        cmd.CommandText = "SELECT COUNT(*) FROM SQLITE_MASTER";
                        cmd.ExecuteScalar();
                    }
                }
                catch
                {
                    try { con.Close(); }
                    catch { }
                }

                //If the db is not open now, it won't open
                if (con.State != System.Data.ConnectionState.Open)
                    throw; //Report original error

                //The open method succeeded with the non-default method, now change the password
                System.Reflection.MethodInfo changePwdMethod = con.GetType().GetMethod("ChangePassword", new Type[] { typeof(string) });
                changePwdMethod.Invoke(con, new object[] { noEncryption ? null : password });
            }
        }
Esempio n. 16
0
        public bool Execute(System.Data.IDbConnection connection, System.Data.IDbTransaction transaction = null)
        {
            if (_processor == null) _processor = new ScriptProcessing.SqlServerScriptProcessor();
            if (connection.State == System.Data.ConnectionState.Closed)
            {
                connection.Open();
            }
            IList<string> bits = _processor.ProcessScript(_script, Parameters);
            foreach (string bit in bits)
            {
                System.Data.IDbCommand cmd = connection.CreateCommand();
                if(transaction!=null) cmd.Transaction = transaction;
                cmd.CommandText = bit;
                cmd.ExecuteNonQuery();
            }

            return true;
        }
Esempio n. 17
0
            public static IEnumerable<ILocalBlockSource> GetFilesAndSourceBlocks(System.Data.IDbConnection connection, string filetablename, string blocktablename, long blocksize, bool skipMetadata)
            {
                using(var cmd = connection.CreateCommand())
                {
                    // TODO: Skip metadata as required
                    cmd.CommandText = string.Format(@"SELECT DISTINCT ""A"".""TargetPath"", ""A"".""ID"", ""B"".""Hash"", (""B"".""Index"" * {2}), ""B"".""Index"", ""B"".""Size"", ""C"".""Path"", (""D"".""Index"" * {2}), ""E"".""Size"", ""B"".""Metadata"" FROM ""{0}"" ""A"", ""{1}"" ""B"", ""File"" ""C"", ""BlocksetEntry"" ""D"", ""Block"" E WHERE ""A"".""ID"" = ""B"".""FileID"" AND ""C"".""BlocksetID"" = ""D"".""BlocksetID"" AND ""D"".""BlockID"" = ""E"".""ID"" AND ""B"".""Hash"" = ""E"".""Hash"" AND ""B"".""Size"" = ""E"".""Size"" AND ""B"".""Restored"" = 0", filetablename, blocktablename, blocksize);
                    using(var rd = cmd.ExecuteReader())
                    {
                        if (rd.Read())
                        {
                            var more = true;
                            while(more)
                            {
                                var f = new LocalBlockSource(rd);
                                string current = f.TargetPath;
                                yield return f;

                                more = f.HasMore;
                                while (more && current == f.TargetPath)
                                    more = rd.Read();
                            }
                        }
                    }
                }
            }
Esempio n. 18
0
 private void RemoverItens(System.Data.IDbConnection conexão, string relação, System.Data.IDbTransaction transação)
 {
     using (var cmd = conexão.CreateCommand())
     {
         cmd.CommandText = string.Format("delete from {0} where producaofiscal = {1}", relação, DbTransformar(Código));
         cmd.Transaction = transação;
         cmd.ExecuteNonQuery();
     }
 }
Esempio n. 19
0
 private void AdicionarSaída(System.Data.IDbConnection conexão, System.Data.IDbTransaction transação, ItemProduçãoFiscal novoItem, decimal qtdReceitas)
 {
     using (var cmd = conexão.CreateCommand())
     {
         cmd.CommandText = SaídaProduçãoFiscal.ObterSqlInserçãoSaída(this, qtdReceitas, novoItem.Referência, novoItem.Quantidade);
         cmd.Transaction = transação;
         cmd.ExecuteNonQuery();
     }
 }
Esempio n. 20
0
 private void AdicionarEntrada(System.Data.IDbConnection conexão, System.Data.IDbTransaction transação, decimal qtdReceitas, Ingrediente ingrediente)
 {
     using (var cmd = conexão.CreateCommand())
     {
         cmd.CommandText = EntradaProduçãoFiscal.ObterSqlInserçãoEntrada(this, ingrediente, qtdReceitas);
         cmd.Transaction = transação;
         cmd.ExecuteNonQuery();
     }
 }
Esempio n. 21
0
		public static byte [] ConsultarBytes(System.Data.IDbConnection conexão, string comando, int bufLen)
		{
			byte [] dados = new byte[bufLen];
            IDataReader leitor = null;

			using (IDbCommand cmd = conexão.CreateCommand())
			{
				cmd.CommandText = comando;

				lock (conexão)
				{
                    Usuários.UsuárioAtual.GerenciadorConexões.RemoverConexão(conexão);
                    try
                    {
                        using (leitor = cmd.ExecuteReader())
                        {
                            leitor.Read();
                            leitor.GetBytes(0, 0, dados, 0, bufLen);
                        }
                    }
                    finally
                    {
                        if (leitor != null)
                            leitor.Close();

                        Usuários.UsuárioAtual.GerenciadorConexões.AdicionarConexão(conexão);
                    }
				}
			}

			return dados;
		}
Esempio n. 22
0
            public DirectBlockMarker(System.Data.IDbConnection connection, string blocktablename, string filetablename, string statstablename)
            {
                m_insertblockCommand = connection.CreateCommand();
                m_resetfileCommand = connection.CreateCommand();
                m_updateAsRestoredCommand = connection.CreateCommand();
                m_updateFileAsDataVerifiedCommand = connection.CreateCommand();
                m_statUpdateCommand = connection.CreateCommand();

                m_insertblockCommand.Transaction = connection.BeginTransaction();
                m_resetfileCommand.Transaction = m_insertblockCommand.Transaction;
                m_updateAsRestoredCommand.Transaction = m_insertblockCommand.Transaction;
                m_updateFileAsDataVerifiedCommand.Transaction = m_insertblockCommand.Transaction;
                m_statUpdateCommand.Transaction = m_insertblockCommand.Transaction;

                m_blocktablename = blocktablename;
                m_filetablename = filetablename;

                m_insertblockCommand.CommandText = string.Format(
                      @"UPDATE ""{0}"" SET ""Restored"" = 1 "
                    + @" WHERE ""FileID"" = ? AND ""Index"" = ? AND ""Hash"" = ? AND ""Size"" = ? AND ""Metadata"" = ? AND ""Restored"" = 0 "
                    , m_blocktablename);
                m_insertblockCommand.AddParameters(5);

                m_resetfileCommand.CommandText = string.Format(
                      @"UPDATE ""{0}"" SET ""Restored"" = 0 WHERE ""FileID"" = ? "
                    , m_blocktablename);
                m_resetfileCommand.AddParameters(1);

                m_updateAsRestoredCommand.CommandText = string.Format(
                      @"UPDATE ""{0}"" SET ""Restored"" = 1 WHERE ""FileID"" = ? AND ""Metadata"" <= ? "
                    , m_blocktablename);
                m_updateAsRestoredCommand.AddParameters(2);

                m_updateFileAsDataVerifiedCommand.CommandText = string.Format(
                      @"UPDATE ""{0}"" SET ""DataVerified"" = 1 WHERE ""ID"" = ?"
                    , m_filetablename);
                m_updateFileAsDataVerifiedCommand.AddParameters(1); 

                if (statstablename != null)
                {
                    // Fields in Stats: TotalFiles, TotalBlocks, TotalSize
                    //                  FilesFullyRestored, FilesPartiallyRestored, BlocksRestored, SizeRestored
                    m_statUpdateCommand.CommandText = string.Format(@"SELECT SUM(""FilesFullyRestored""), SUM(""SizeRestored"") FROM ""{0}"" ", statstablename);
                }
                else // very slow fallback if stats tables were not created
                    m_statUpdateCommand.CommandText = string.Format(@"SELECT COUNT(DISTINCT ""FileID""), SUM(""Size"") FROM ""{0}"" WHERE ""Restored"" = 1 ", m_blocktablename);

            }
        private static void _insertManually(TypeWithByteArrayField orig, System.Data.IDbConnection db)
        {
            using(var cmd = db.CreateCommand()) {
                cmd.CommandText = @"INSERT INTO ""TypeWithByteArrayField"" (""Id"",""Content"") VALUES (@Id, @Content) --manual parameterized insert";

                var p_id = cmd.CreateParameter();
                p_id.ParameterName = "@Id";
                p_id.Value = orig.Id;

                cmd.Parameters.Add(p_id);

                var p_content = cmd.CreateParameter();
                p_content.ParameterName = "@Content";
                p_content.Value = orig.Content;

                cmd.Parameters.Add(p_content);

                cmd.ExecuteNonQuery();
            }
        }
Esempio n. 24
0
        private void GetAlbumTracksByTitelId(Album album, System.Data.EntityClient.EntityConnection entityConnection)
        {
            if (album != null)
            {
                StringBuilder stringBuilder = new StringBuilder();
                stringBuilder.Append("SELECT t.LiedID, t.Track, t.Lied ,t.Dauer");
                stringBuilder.Append(" FROM tunesEntities.lieder AS t");
                stringBuilder.Append(" WHERE t.titelid = @albumId");
                stringBuilder.Append(" AND t.Liedpfad IS NOT NULL");
                stringBuilder.Append(" ORDER BY t.Track");
                string sql = stringBuilder.ToString();

                using (EntityCommand entityCommand = entityConnection.CreateCommand())
                {
                    EntityParameter id = new EntityParameter();
                    id.ParameterName = "albumid";
                    id.Value = album.Id;
                    entityCommand.Parameters.Add(id);
                    entityCommand.CommandText = sql;

                    List<Track> tracks = null;
                    using (EntityDataReader dataReader = entityCommand.ExecuteReader(System.Data.CommandBehavior.SequentialAccess))
                    {
                        while (dataReader.Read())
                        {
                            if (tracks == null)
                            {
                                tracks = new List<Track>();
                            }
                            Track track = new Track
                            {
                                Id = dataReader.GetInt32("LiedID", false, 0),
                                TrackNumber = dataReader.GetInt32("Track", false, 0),
                                Name = dataReader.GetString("Lied", false, string.Empty),
                                Duration = dataReader.GetTimeSpan("Dauer", true, TimeSpan.MinValue)
                            };
                            tracks.Add(track);
                        }
                        if (tracks != null)
                        {
                            album.Tracks = tracks.ToArray();
                        }
                    }
                }
            }
        }
Esempio n. 25
0
 public void SetDataTableColumnsFromDB(System.Data.DataTable dt, System.Data.SqlClient.SqlConnection conn,string tabName)
 {
     SqlCommand sqlCmd = conn.CreateCommand();
     sqlCmd.CommandText = @"SELECT top 0 [dmac],[mac],[ip],[time],[hitId],[refhitId],[uid],[posidx],[pagetime],[day_id],[indb_datetime],[indw_datetime], [client_os],
     [mobile_brand],[client_browser], [version], [groupid],[pagetime2] FROM " + tabName;
     dt.Load(sqlCmd.ExecuteReader());
 }
 private static void _selectAndVerifyManually(TypeWithByteArrayField orig, System.Data.IDbConnection db)
 {
     using(var cmd = db.CreateCommand()) {
         cmd.CommandText = @"select ""Content"" from ""TypeWithByteArrayField"" where ""Id"" = 1 --manual select";
         using(var reader = cmd.ExecuteReader()) {
             reader.Read();
             var ba = reader["Content"] as byte[];
             Assert.AreEqual(orig.Content.Length, ba.Length);
             Assert.AreEqual(orig.Content, ba);
         }
     }
 }
        private User RetrieveUser(System.Data.IDbConnection conn, string username)
        {
            using (System.Data.IDbCommand cmd = conn.CreateCommand())
            {
                cmd.CommandType = System.Data.CommandType.Text;
                cmd.CommandText = this.SelectUserSQL(username);
                using (System.Data.IDataReader dr = cmd.ExecuteReader())
                {
                    if (!dr.Read()) return null;

                    string uname = RetrieveFieldString(dr, "user_name");
                    string kpirole = RetrieveFieldString(dr, "kpi_role_name");
                    string locations_packed = RetrieveFieldString(dr, "kpi_plants");

                    User user = new User
                    {
                        Username = uname.Trim(),
                        Role = kpirole.Trim(),
                        Locations = new string[] { }
                    };

                    if (!string.IsNullOrEmpty(locations_packed))
                    {
                        // gotta whack the empy last entry (padded with 20 spaces)
                        // there must be a more elegant way to do this!
                        string[] locations = locations_packed.Split(cDelimitter);
                        user.Locations = new string[locations.Length - 1];
                        for (int i = 0; i<locations.Length -1; i++)
                            user.Locations[i] = locations[i].Trim();
                    }
                    return user;
                }
            }
        }
Esempio n. 28
0
			public BlockQuery(System.Data.IDbConnection con, Options options, System.Data.IDbTransaction transaction)
			{
				m_command = con.CreateCommand();
				m_command.Transaction = transaction;
				
				if (options.BlockHashLookupMemory > 0)
				{
					m_lookup = new HashLookupHelper<long>((ulong)options.BlockHashLookupMemory);
					using(var reader = m_command.ExecuteReader(@"SELECT ""Hash"", ""Size"" FROM ""Block"" "))
					while (reader.Read())
					{
						var hash = reader.GetValue(0).ToString();
						var size = Convert.ToInt64(reader.GetValue(1));
						m_lookup.Add(hash, size, size);
					}
				}
				
				m_command.Parameters.Clear();
				m_command.CommandText = @"SELECT ""VolumeID"" FROM ""Block"" WHERE ""Hash"" = ? AND ""Size"" = ? ";
				m_command.AddParameters(2);
			}
        private KPIRole RetrieveRole(System.Data.IDbConnection conn, string rolename)
        {
            using (System.Data.IDbCommand cmd = conn.CreateCommand())
            {
                cmd.CommandType = System.Data.CommandType.Text;
                cmd.CommandText = this.SelectRoleSQL(rolename);
                using (System.Data.IDataReader dr = cmd.ExecuteReader())
                {
                    if (!dr.Read()) return null;

                    string kpis_packed = RetrieveFieldString(dr, "kpi_codes");
                    string displays_packed = RetrieveFieldString(dr, "kpi_display_codes");
                    string timers_packed = RetrieveFieldString(dr, "kpi_display_timers");

                    KPIRole role = new KPIRole
                    {
                        Name = rolename,
                        KPIs = new KPIDisplay[] { }
                    };

                    if (!string.IsNullOrEmpty(kpis_packed))
                    {
                        string[] kpis = kpis_packed.Split(cDelimitter);
                        string[] displays = !string.IsNullOrEmpty(displays_packed) ? displays_packed.Split(cDelimitter) : new string[] {};
                        string[] timers = !string.IsNullOrEmpty(timers_packed) ? timers_packed.Split(cDelimitter) : new string[] {};

                        role.KPIs = new KPIDisplay[kpis.Length];

                        int t = 0;
                        for (int i = 0; i<kpis.Length && i<displays.Length; i++)
                        {
                            DateTime? starttime = null;
                            DateTime? endtime = null;
                            if (t < timers.Length && !string.IsNullOrEmpty(timers[t]))
                            {
                                string[] tparts = timers[t++].Split('-');
                                if (tparts.Length > 0)
                                    starttime = DateTime.Parse(DateTime.Today.ToShortDateString() + " " + tparts[0]);
                                if (tparts.Length > 1)
                                    endtime = DateTime.Parse(DateTime.Today.ToShortDateString() + " " + tparts[1]);
                            }

                            role.KPIs[i] = new KPIDisplay
                            {
                                Code = kpis[i].Trim(),
                                Display = displays[i].Trim(),
                                StartTime = starttime,
                                EndTime = endtime,
                                KPI = new Models.KPI {
                                    Code = kpis[i].Trim(),
                                    Description = string.Empty,
                                    Category = string.Empty,
                                    Actual = 0M,
                                    Units = 0M,
                                    Target = 0M,
                                    Level1 = 0M,
                                    Level2 = 0M
                                }
                            };
                        }
                    }
                    return role;
                }
            }
        }