public string CarregaAnexo(string usuario, DateTime data, string codigo) { Byte[] conteudo; FileStream fs = null; FbCommand cmd = new FbCommand("select des_conteudo,des_arq_anexo from anexos " + "where COD_USUARIO='" + usuario + "' and " + " DAT_AGENDAMENTO='" + data.ToString("M/d/yyyy HH:mm:ss") + "' and " + " COD_ANEXO='" + codigo + "'", Globais.bd); FbDataReader reader = cmd.ExecuteReader(CommandBehavior.SingleRow); if (!reader.Read()) { return(null); } string arq = reader.GetString(1).Trim(); string ext = ""; int i = arq.LastIndexOf('.'); if (i > 0) { ext = arq.Substring(i, arq.Length - i); } conteudo = new Byte[(reader.GetBytes(0, 0, null, 0, int.MaxValue))]; reader.GetBytes(0, 0, conteudo, 0, conteudo.Length); reader.Close(); //fs = new FileStream("tmp_" + codigo + ext, FileMode.Create, FileAccess.Write); fs = new FileStream("anexo" + ext, FileMode.Create, FileAccess.Write); fs.Write(conteudo, 0, conteudo.Length); fs.Close(); //return "tmp_" + codigo + ext; return("anexo" + ext); }
public void LoadAllCars() { fb_con.Open(); string sql = "SELECT * FROM CARS ORDER BY ID"; FbCommand cmd = new FbCommand(sql, fb_con); car onecar; int tempInt; using (FbDataReader r = cmd.ExecuteReader()) { while (r.Read()) { onecar = new car(); onecar.ID = r.GetInt32(0); onecar.REGNUMBER = r.GetString(1); onecar.CARMODEL = r.GetString(2); onecar.CHECKUPDATE = r.GetString(3); //BLOB READING onecar.PHOTO = new byte[(r.GetBytes(4, 0, null, 0, int.MaxValue))]; if (onecar.PHOTO.Length > 0) { r.GetBytes(0, 0, onecar.PHOTO, 0, onecar.PHOTO.Length); } ///////////////////// onecar.NOTE = r.GetString(5); onecar.CREATEWHO = r.GetString(6); onecar.CREATEWHEN = r.GetString(7); onecar.CHANGEWHO = r.GetString(8); onecar.CHANGEWHEN = r.GetString(9); onecar.DEPARTMENTID = r.GetInt32(10); if (int.TryParse(r.GetString(11), out tempInt)) { onecar.TANK1 = tempInt; } if (int.TryParse(r.GetString(12), out tempInt)) { onecar.TANK2 = tempInt; } if (int.TryParse(r.GetString(13), out tempInt)) { onecar.MAXCONSUMPTPH = tempInt; } if (int.TryParse(r.GetString(14), out tempInt)) { onecar.CSTABILITYTIME = tempInt; } if (int.TryParse(r.GetString(15), out tempInt)) { onecar.NOMINALRPM = tempInt; } carsArray.Add(onecar); } } fb_con.Close(); }
public void LoadAllWorkers() { fb_con.Open(); string sql = "SELECT * FROM WORKERS ORDER BY ID"; FbCommand cmd = new FbCommand(sql, fb_con); worker oneworker; DateTime dateTemp = new DateTime(); using (FbDataReader r = cmd.ExecuteReader()) { int i; while (r.Read()) { i = 0; oneworker = new worker(); oneworker.ID = r.GetInt32(i++); oneworker.WORKERINTID = r.GetInt32(i++); oneworker.DEPARTMENTID = r.GetInt32(i++); oneworker.FIRSTNAME = r.GetString(i++); oneworker.SURNAME = r.GetString(i++); oneworker.MIDDLENAME = r.GetString(i++); if (DateTime.TryParse(r.GetString(i++), out dateTemp)) { oneworker.BIRTHDAY = dateTemp; } oneworker.PASSPORT = r.GetString(i++); oneworker.LICENCE = r.GetString(i++); if (DateTime.TryParse(r.GetString(i++), out dateTemp)) { oneworker.DATEDUELICENCE = dateTemp; } oneworker.CATHEGORIES = r.GetString(i++); oneworker.MEDICALCERTIFICATE = r.GetString(i++); if (DateTime.TryParse(r.GetString(i++), out dateTemp)) { oneworker.DATEDUEMEDICAL = dateTemp; } //BLOB READING oneworker.PHOTO = new byte[(r.GetBytes(i++, 0, null, 0, int.MaxValue))]; if (oneworker.PHOTO.Length > 0) { r.GetBytes(0, 0, oneworker.PHOTO, 0, oneworker.PHOTO.Length); } ///////////////////// oneworker.NOTES = r.GetString(i++); oneworker.CREATEWHO = r.GetString(i++); oneworker.CREATEWHEN = r.GetString(i++); oneworker.CHANGEWHO = r.GetString(i++); oneworker.CHANGEWHEN = r.GetString(i++); workers.Add(oneworker); } } fb_con.Close(); }
//============================================================================ /// <summary> /// /// </summary> /// <param name="col"></param> /// <returns></returns> //============================================================================ public override byte[] ColAsBytes(int col) { Byte[] result = new Byte[1]; if (reader != null) { if (reader.FieldCount >= col + 1) { long size = reader.GetBytes(col, 0, null, 0, 0); result = new Byte[size]; reader.GetBytes(col, 0, result, 0, (int)size); } } return(result); }
public void ReaderGetBytes() { int id_value = GetId(); string selectText = "SELECT blob_field FROM TEST WHERE int_field = " + id_value.ToString(); string insertText = "INSERT INTO TEST (int_field, blob_field) values(@int_field, @blob_field)"; Console.WriteLine("\r\n\r\nFbDataReader.GetBytes with Binary Blob Test"); Console.WriteLine("Generating an array of temp data"); // Generate an array of temp data byte[] insert_values = new byte[100000 * 4]; RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider(); rng.GetBytes(insert_values); Console.WriteLine("Executing insert command"); // Execute insert command FbTransaction transaction = Connection.BeginTransaction(); FbCommand insert = new FbCommand(insertText, Connection, transaction); insert.Parameters.Add("@int_field", FbDbType.Integer).Value = id_value; insert.Parameters.Add("@blob_field", FbDbType.Binary).Value = insert_values; insert.ExecuteNonQuery(); transaction.Commit(); Console.WriteLine("Checking inserted values"); // Check that inserted values are correct FbCommand select = new FbCommand(selectText, Connection); byte[] select_values = new byte[100000 * 4]; using (FbDataReader reader = select.ExecuteReader()) { int index = 0; int segmentSize = 1000; while (reader.Read()) { while (index < 400000) { reader.GetBytes(0, index, select_values, index, segmentSize); index += segmentSize; } } } for (int i = 0; i < insert_values.Length; i++) { if (insert_values[i] != select_values[i]) { throw new Exception("differences at index " + i.ToString()); } } }
private void GetPropertyValuesFromDatabase(string userName, SettingsPropertyValueCollection svc) { HttpContext context = HttpContext.Current; string[] names = null; string values = null; byte[] buf = null; string sName = null; if (context != null) { sName = (context.Request.IsAuthenticated ? context.User.Identity.Name : context.Request.AnonymousID); } using (FbConnection conn = new FbConnection(this.connectionString)) { conn.Open(); using (FbCommand cmd = new FbCommand("Profiles_GetProperties", conn)) { cmd.CommandTimeout = this.commandTimeout; cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Add(CreateInputParam("@ApplicationName", FbDbType.VarChar, ApplicationName)); cmd.Parameters.Add(CreateInputParam("@UserName", FbDbType.VarChar, userName)); cmd.Parameters.Add(CreateInputParam("@CurrentTimeUtc", FbDbType.Date, DateTime.UtcNow)); using (FbDataReader reader = cmd.ExecuteReader(CommandBehavior.SingleRow)) { if (reader.Read()) { names = reader.GetString(0).Split(':'); values = reader.GetString(1); int size = (int)reader.GetBytes(2, 0, null, 0, 0); buf = new byte[size]; reader.GetBytes(2, 0, buf, 0, size); } } } ParseDataFromDB(names, values, buf, svc); } }
public void GetBytesLengthTest() { string sql = "select blob_field from TEST where int_field = @int_field"; FbCommand command = new FbCommand(sql, this.Connection); command.Parameters.Add("@int_field", FbDbType.Integer).Value = 2; FbDataReader reader = command.ExecuteReader(); reader.Read(); long length = reader.GetBytes(0, 0, null, 0, 0); reader.Close(); Assert.AreEqual(13, length, "Incorrect blob length"); }
static void Main(string[] args) { string tmpString = string.Empty; StreamWriter fstr_out = null; FbConnection cn = null; FbCommand cmd = null; FbDataReader rdr = null; FbDataAdapter da = null; DataTable tmpDataTable = null; object tmpObject; int tmpInt = int.MinValue; long tmpLong = long.MinValue; try { try { fstr_out = new StreamWriter("log.log", false, System.Text.Encoding.GetEncoding(1251)); fstr_out.AutoFlush = true; ConnectionStringSettingsCollection connectionStrings = ConfigurationManager.ConnectionStrings; if (connectionStrings != null) { try { tmpString = connectionStrings["FirebirdServer"].ConnectionString; } catch { tmpString = string.Empty; } } cn = new FbConnection(tmpString); cn.StateChange += new StateChangeEventHandler(conn_StateChange); cn.InfoMessage += new FbInfoMessageEventHandler(conn_InfoMessage); cn.Open(); fstr_out.WriteLine("ConnectionString: " + cn.ConnectionString); fstr_out.WriteLine("ConnectionTimeout: " + cn.ConnectionTimeout.ToString()); fstr_out.WriteLine("Database: " + cn.Database); fstr_out.WriteLine("DataSource: " + cn.DataSource); fstr_out.WriteLine("PacketSize: " + cn.PacketSize); fstr_out.WriteLine("ServerVersion: " + cn.ServerVersion); fstr_out.WriteLine("State: " + cn.State.ToString()); fstr_out.WriteLine(); #if TEST_COMMENT if (cmd == null) { cmd = cn.CreateCommand(); } cmd.CommandType = CommandType.Text; cmd.CommandText = "select 5/**/*3 from rdb$database"; tmpObject = cmd.ExecuteScalar(); #endif #if TEST_SMTH if (cmd == null) { cmd = cn.CreateCommand(); } cmd.CommandType = CommandType.Text; cmd.CommandText = "select * from TestDate order by FDate"; cmd.Parameters.Clear(); if (da == null) { da = new FbDataAdapter(cmd); } else { da.SelectCommand = cmd; } if (tmpDataTable != null) { tmpDataTable.Reset(); } else { tmpDataTable = new DataTable(); } da.Fill(tmpDataTable); tmpString = ""; for (int i = 0; i < tmpDataTable.Rows.Count; ++i) { if (tmpString != string.Empty) { tmpString += " "; } tmpString += Convert.ToDateTime(tmpDataTable.Rows[i]["FDate"]).ToString("yyyy-MM-dd"); } #endif if (tmpDataTable != null) { tmpDataTable.Reset(); } else { tmpDataTable = new DataTable(); } fstr_out.WriteLine("FbConnection.GetSchema()"); tmpDataTable = cn.GetSchema(); tmpString = string.Empty; foreach (DataColumn col in tmpDataTable.Columns) { if (tmpString != string.Empty) { tmpString += "\t"; } tmpString += col.ColumnName; } fstr_out.WriteLine("\t" + tmpString); foreach (DataRow row in tmpDataTable.Rows) { tmpString = string.Empty; foreach (DataColumn col in tmpDataTable.Columns) { if (tmpString != string.Empty) { tmpString += "\t"; } tmpString += !row.IsNull(col.ColumnName) ? row[col.ColumnName] : "NULL"; } fstr_out.WriteLine("\t" + tmpString); } fstr_out.WriteLine(); cmd = cn.CreateCommand(); cmd.Transaction = cn.BeginTransaction(new FbTransactionOptions { TransactionBehavior = FbTransactionBehavior.ReadCommitted } /*IsolationLevel.ReadCommitted*/); cmd.CommandType = CommandType.Text; cmd.CommandText = "select * from \"Staff\""; rdr = cmd.ExecuteReader(); do { if (rdr.HasRows) { for (int i = 0; i < rdr.FieldCount; ++i) { fstr_out.WriteLine(rdr.GetName(i) + " GetDataTypeName(): \"" + rdr.GetDataTypeName(i) + "\" GetFieldType(): \"" + rdr.GetFieldType(i) + "\""); } while (rdr.Read()) { fstr_out.WriteLine(rdr["Name"] + " " + rdr["Salary"]); } } } while (rdr.NextResult()); rdr.Close(); if (tmpDataTable != null) { tmpDataTable.Reset(); } else { tmpDataTable = new DataTable(); } if (da != null) { da.SelectCommand = cmd; } else { da = new FbDataAdapter(cmd); } da.Fill(tmpDataTable); foreach (DataRow row in tmpDataTable.Rows) { fstr_out.WriteLine(row["Name"] + " " + row["Salary"]); } #if TEST_STORED_PROCEDURES if (cmd == null) { cmd = cn.CreateCommand(); } cmd.CommandType = CommandType.StoredProcedure; cmd.CommandText = "SP1"; FbCommandBuilder.DeriveParameters(cmd); for (int i = 0; i < cmd.Parameters.Count; ++i) { fstr_out.WriteLine(cmd.Parameters[i].ParameterName + " " + cmd.Parameters[i].Direction + " " + cmd.Parameters[i].FbDbType + " " + cmd.Parameters[i].DbType); } cmd.Parameters["@ARGFIRST"].Value = 7; cmd.Parameters["@ARGSECOND"].Value = 8; cmd.ExecuteNonQuery(); if (!Convert.IsDBNull(cmd.Parameters["@RESULT"].Value)) { fstr_out.WriteLine(cmd.Parameters["@RESULT"].Value); } cmd.CommandText = "SP1_1"; FbCommandBuilder.DeriveParameters(cmd); cmd.Parameters["@ARGFIRST"].Value = 20; cmd.Parameters["@ARGSECOND"].Value = 8; cmd.ExecuteNonQuery(); if (!Convert.IsDBNull(cmd.Parameters["@RESULT"].Value)) { fstr_out.WriteLine(cmd.Parameters["@RESULT"].Value); } cmd.CommandType = CommandType.Text; cmd.CommandText = "select * from SP1_1 (?, ?)"; cmd.Parameters.Clear(); FbParameter tmpParameter; tmpParameter = cmd.CreateParameter(); tmpParameter.Direction = ParameterDirection.Input; tmpParameter.DbType = DbType.Decimal; tmpParameter.ParameterName = "@ARGSECOND"; tmpParameter.Value = 8; cmd.Parameters.Add(tmpParameter); tmpParameter = cmd.CreateParameter(); tmpParameter.Direction = ParameterDirection.Input; tmpParameter.DbType = DbType.Decimal; tmpParameter.ParameterName = "@ARGFIRST"; tmpParameter.Value = 20; cmd.Parameters.Add(tmpParameter); if ((tmpObject = cmd.ExecuteScalar()) != null && !Convert.IsDBNull(tmpObject)) { tmpInt = Convert.ToInt32(tmpObject); } fstr_out.WriteLine(tmpInt); if (tmpDataTable != null) { tmpDataTable.Reset(); } else { tmpDataTable = new DataTable(); } if (da != null) { da.SelectCommand = cmd; } else { da = new FbDataAdapter(cmd); } da.Fill(tmpDataTable); cmd.CommandType = CommandType.StoredProcedure; cmd.CommandText = "SP2"; FbCommandBuilder.DeriveParameters(cmd); for (int i = 0; i < cmd.Parameters.Count; ++i) { fstr_out.WriteLine(cmd.Parameters[i].ParameterName + " " + cmd.Parameters[i].Direction + " " + cmd.Parameters[i].FbDbType + " " + cmd.Parameters[i].DbType); } cmd.Parameters["@TESTID"].Value = 1; if (tmpDataTable != null) { tmpDataTable.Reset(); } else { tmpDataTable = new DataTable(); } if (da != null) { da.SelectCommand = cmd; } else { da = new FbDataAdapter(cmd); } da.Fill(tmpDataTable); /* * cmd.CommandType = CommandType.Text; * cmd.CommandText = "{call SP2(?, ?)}"; * cmd.Parameters.Clear(); * * tmpParameter = cmd.CreateParameter(); * tmpParameter.Direction = ParameterDirection.Input; * tmpParameter.DbType = DbType.Int32; * tmpParameter.ParameterName = "@TESTID"; * tmpParameter.Value = 1; * cmd.Parameters.Add(tmpParameter); * * tmpParameter = cmd.CreateParameter(); * tmpParameter.Direction = ParameterDirection.Output; * tmpParameter.DbType = DbType.String; * tmpParameter.ParameterName = "@TESTVALUE"; * cmd.Parameters.Add(tmpParameter); * * if (tmpDataTable != null) * tmpDataTable.Reset(); * else * tmpDataTable = new DataTable(); * * if (da != null) * da.SelectCommand = cmd; * else * da = new FbDataAdapter(cmd); * * da.Fill(tmpDataTable); */ cmd.Parameters.Clear(); cmd.CommandType = CommandType.Text; //cmd.CommandText = "\"Stub\""; //error //cmd.CommandText = "exec \"Stub\""; //error //cmd.CommandText = "execute \"Stub\""; //error cmd.CommandText = "execute procedure \"Stub\""; cmd.ExecuteNonQuery(); //cmd.CommandText = "{call \"Stub\"}"; //error //cmd.ExecuteNonQuery(); #endif #if TEST_BLOB cmd.CommandType = CommandType.Text; FileStream fs; byte[] Blob; #if TEST_BLOB_SAVE cmd.CommandText = "update \"TestDataTypes\" set \"CBlob\" = @CBlob"; cmd.Parameters.Clear(); cmd.Parameters.Add("@CBlob", FbDbType.Binary); fs = new FileStream("welcome.bmp", FileMode.Open, FileAccess.Read); Blob = new byte[fs.Length]; fs.Read(Blob, 0, Blob.Length); cmd.Parameters["@CBlob"].Value = Blob; tmpInt = cmd.ExecuteNonQuery(); #endif cmd.CommandText = "select * from \"TestDataTypes\""; cmd.Parameters.Clear(); rdr = cmd.ExecuteReader(); do { if (rdr.HasRows) { for (int i = 0; i < rdr.FieldCount; ++i) { fstr_out.WriteLine(rdr.GetName(i) + " GetDataTypeName(): \"" + rdr.GetDataTypeName(i) + "\" GetFieldType(): \"" + rdr.GetFieldType(i) + "\""); } tmpInt = rdr.GetOrdinal("CBlob"); while (rdr.Read()) { tmpString = "FromBlob.bmp"; if (File.Exists(tmpString)) { File.Delete(tmpString); } if (!rdr.IsDBNull(tmpInt)) { Blob = (byte[])rdr["CBlob"]; fs = new FileStream(tmpString, FileMode.Create); fs.Write(Blob, 0, Blob.Length); fs.Close(); } tmpString = "FromBlob_1.bmp"; if (File.Exists(tmpString)) { File.Delete(tmpString); } if (!rdr.IsDBNull(tmpInt)) { tmpLong = rdr.GetBytes(tmpInt, 0, null, 0, int.MaxValue); Blob = new byte[tmpLong]; rdr.GetBytes(tmpInt, 0, Blob, 0, Blob.Length); fs = new FileStream(tmpString, FileMode.Create); fs.Write(Blob, 0, Blob.Length); fs.Close(); } } } } while (rdr.NextResult()); rdr.Close(); #endif cmd.Transaction.Rollback(); /* * cn.ChangeDatabase("E:\\USI.Fil\\Base\\NODE.IB6"); * fstr_out.WriteLine(conn.Database); * * cmd.Transaction = conn.BeginTransaction(IsolationLevel.ReadCommitted); * * cmd.CommandType = CommandType.Text; * cmd.CommandText = "select * from \"Filial\""; * tmpDataTable.Reset(); * da.Fill(tmpDataTable); * * cmd.Transaction.Rollback(); */ cmd = null; cn.Close(); } catch (Exception eException) { Console.WriteLine(eException.GetType().FullName + Environment.NewLine + "Message: " + eException.Message + Environment.NewLine + "StackTrace:" + Environment.NewLine + eException.StackTrace); } } finally { if (rdr != null && !rdr.IsClosed) { rdr.Close(); } if (cmd != null) { cmd.Transaction.Rollback(); } if (cn != null && cn.State == ConnectionState.Open) { cn.Close(); } if (fstr_out != null) { fstr_out.Close(); } } }
public static string RetornaBlob(string sQuery) { string texto = ""; FbConnection Conn = HlpDbFuncoesGeral.conexao; FbCommand comando = new FbCommand(sQuery.ToString(), Conn); if (Conn.State == ConnectionState.Closed) { Conn.Open(); } FbDataReader Reader = comando.ExecuteReader(); Byte[] blob = null; MemoryStream ms = new MemoryStream(); while (Reader.Read()) { blob = new Byte[(Reader.GetBytes(0, 0, null, 0, int.MaxValue))]; try { Reader.GetBytes(0, 0, blob, 0, blob.Length); } catch { texto = ""; } ms = new MemoryStream(blob); } Conn.Close(); StreamReader Ler = new StreamReader(ms); Ler.ReadLine(); while (Ler.Peek() != -1) { texto += Ler.ReadLine(); } if ((Acesso.NM_EMPRESA == "MACROTEX") || (Acesso.NM_EMPRESA == "PAVAX")) { string sVendedor = string.Empty; string sPedidoCliente = string.Empty; if (Conn.State != ConnectionState.Open) { Conn.Open(); } FbCommand cmd = new FbCommand(sQuery.ToString().Replace("nf.ds_anota ,", ""), Conn); cmd.ExecuteNonQuery(); FbDataReader dr = cmd.ExecuteReader(); dr.Read(); sVendedor = dr["nm_vend"].ToString(); sPedidoCliente = dr["DS_DOCORIG"].ToString(); if ((Acesso.NM_EMPRESA == "MACROTEX")) { if (texto == "") { texto += string.Format("Vendedor.: {0} Pedido N.: {1}", sVendedor, sPedidoCliente); } else { texto += string.Format(" Vendedor.: {0} Pedido N.: {1}", sVendedor, sPedidoCliente); } } else { if (texto == "") { texto += string.Format("Pedido N.: {0}", sPedidoCliente); } else { texto += string.Format(" Pedido N.: {0}", sPedidoCliente); } } } if (((Acesso.NM_EMPRESA == "MOGPLAST") || (Acesso.NM_EMPRESA == "TSA")) && (Acesso.CD_EMPRESA == "003")) { string sNFOrigem = string.Empty; string sEmiOrigem = string.Empty; if (Conn.State != ConnectionState.Open) { Conn.Open(); } FbCommand cmd = new FbCommand(sQuery.ToString().Replace("nf.ds_anota ,", ""), Conn); cmd.ExecuteNonQuery(); FbDataReader dr = cmd.ExecuteReader(); dr.Read(); //Claudinei - o.s. sem - 02/03/2010 if (dr["cd_nfseq_fat_origem"].ToString() != "") { //Fim - Claudinei - o.s. sem - 02/03/2010 StringBuilder sSqlNFOrigem = new StringBuilder(); sSqlNFOrigem.Append("Select "); sSqlNFOrigem.Append("cd_notafis, "); sSqlNFOrigem.Append("dt_emi "); sSqlNFOrigem.Append("From NF "); sSqlNFOrigem.Append("Where nf.cd_empresa = '"); sSqlNFOrigem.Append("001"); sSqlNFOrigem.Append("'"); sSqlNFOrigem.Append(" and "); sSqlNFOrigem.Append("cd_nfseq = '"); sSqlNFOrigem.Append(dr["cd_nfseq_fat_origem"].ToString()); sSqlNFOrigem.Append("'"); FbCommand cmdNFOrigem = new FbCommand(sSqlNFOrigem.ToString(), Conn); cmdNFOrigem.ExecuteNonQuery(); FbDataReader drNFOrigem = cmdNFOrigem.ExecuteReader(); drNFOrigem.Read(); sNFOrigem = drNFOrigem["cd_notafis"].ToString(); sEmiOrigem = System.DateTime.Parse(drNFOrigem["dt_emi"].ToString()).ToString("dd/MM/yyyy"); if (texto == "") { texto += string.Format("DEV TOTAL REF A NF {0} DE {1}", sNFOrigem, sEmiOrigem); } else { texto += string.Format(" DEV TOTAL REF A NF {0} DE {1}", sNFOrigem, sEmiOrigem); } } } return Util.TiraCaracterEstranho(texto).Trim(); }