EntityDataReader to ToList() - c#-4.0

my code :
public List<Book> GetBook(string Field, object Value)
{
using (EntityConnection conn = new EntityConnection("name=Entities"))
{
conn.Open();
// Create an EntityCommand.
using (EntityCommand cmd = conn.CreateCommand())
{
cmd.CommandText = "Select VALUE b FROM Entities.Book as b where Cast(b." + Field + " as Edm.String) like '%" + Value.ToString() + "%'";
// Execute the command.
using (EntityDataReader rdr =
cmd.ExecuteReader(CommandBehavior.SequentialAccess))
{
conn.Close();
var s = from d in rdr.OfType<Book>().AsEnumerable()
select d;
return (s.ToList());
}
}
}
return (null);
}
why The result is always empty???
What is the correct code?

Why are you closing connection before you started to read from the reader? Reader is like cursor - it doesn't buffer all results to memory when you open it but it loads them incrementally so you could easily terminate connection (and reading functionality as well) before you read any result. You don't have to close the connection explicitly - that is responsibility of using block.
You can also use SQL profiler to validate the it really builds the query you expect.
using (EntityConnection conn = new EntityConnection("name=Entities"))
{
conn.Open();
// Create an EntityCommand.
using (EntityCommand cmd = conn.CreateCommand())
{
cmd.CommandText = "Select VALUE b FROM Entities.Book as b where Cast(b." + Field + " as Edm.String) like '%" + Value.ToString() + "%'";
// Execute the command.
using (EntityDataReader rdr =
cmd.ExecuteReader(CommandBehavior.SequentialAccess))
{
var s = from d in rdr.OfType<Book>().AsEnumerable()
select d;
return (s.ToList());
}
}
}
s.ToList().Count returns 0 because rdr.OfType<Book> is always empty collection. EntitDataReader doesn't materialize entities - it is just wrapper about database related DataReader and it works in the same way. You must read columns and fill them to properties of your entity.
If you don't want to do it you can use objectContext.Translate method but once you start to work with ObjectContext you don't need EntityCommand and EntityDataReader at all.

Related

is it possible to connect to java jOOQ DB?

I discovered a new interesting service and I'm trying to understand how it works. Please explain how to connect to my jOOQ database from another program?
MockDataProvider provider = new MyProvider();
MockConnection connection = new MockConnection(provider);
DSLContext create = DSL.using(connection, SQLDialect.H2);
Field<Integer> id = field(name("BOOK", "ID"), SQLDataType.INTEGER);
Field<String> book = field(name("BOOK", "NAME"), SQLDataType.VARCHAR);
So, I create but can I connect to it?
Here I have added your code, Lukas.
try (Statement s = connection.createStatement();
ResultSet rs = s.executeQuery("SELECT ...")
) {
while (rs.next())
System.out.println(rs.getString(1));
}
This example was found here
https://www.jooq.org/doc/3.7/manual/tools/jdbc-mocking/
public class MyProvider implements MockDataProvider {
#Override
public MockResult[] execute(MockExecuteContext ctx) throws SQLException {
// You might need a DSLContext to create org.jooq.Result and org.jooq.Record objects
//DSLContext create = DSL.using(SQLDialect.ORACLE);
DSLContext create = DSL.using(SQLDialect.H2);
MockResult[] mock = new MockResult[1];
// The execute context contains SQL string(s), bind values, and other meta-data
String sql = ctx.sql();
// Dynamic field creation
Field<Integer> id = field(name("AUTHOR", "ID"), SQLDataType.INTEGER);
Field<String> lastName = field(name("AUTHOR", "LAST_NAME"), SQLDataType.VARCHAR);
// Exceptions are propagated through the JDBC and jOOQ APIs
if (sql.toUpperCase().startsWith("DROP")) {
throw new SQLException("Statement not supported: " + sql);
}
// You decide, whether any given statement returns results, and how many
else if (sql.toUpperCase().startsWith("SELECT")) {
// Always return one record
Result<Record2<Integer, String>> result = create.newResult(id, lastName);
result.add(create
.newRecord(id, lastName)
.values(1, "Orwell"));
mock[0] = new MockResult(1, result);
}
// You can detect batch statements easily
else if (ctx.batch()) {
// [...]
}
return mock;
}
}
I'm not sure what lines 3-5 of your example are supposed to do, but if you implement your MockDataProvider and put that into a MockConnection, you just use that like any other JDBC connection, e.g.
try (Statement s = connection.createStatement();
ResultSet rs = s.executeQuery("SELECT ...")
) {
while (rs.next())
System.out.println(rs.getString(1));
}

Save serial number in Excel using WPF (OLEDB)

My application in WPF allows user to save some data from text boxes into Excel file (using OLEDB connection). I wish to add feature that every time new row is saved into Excel file a sequence number is added into EventID column in that Excel file.
But I'm getting an error while running the application related to parameter #EventId saying: 'parameter has no default value'.
I expect I have written wrong sql1 command to generate the serial number.
I'd appreciate your help.
private void btnSaveNewEvent1_Click_1(object sender, RoutedEventArgs e)
{
object eventName = txtEventName.Text;
object typeValue = txtEventType.Text;
object nameValue = txtAttributeName.Text;
object attribvValue = txtAValue.Text;
object descValue = txtEventDescrip.Text;
System.Data.OleDb.OleDbConnection MyConnection;
System.Data.OleDb.OleDbCommand myCommand = new System.Data.OleDb.OleDbCommand();
System.Data.OleDb.OleDbCommand myCommand1 = new System.Data.OleDb.OleDbCommand();
String sql = null;
String sql1 = null;
MyConnection = new System.Data.OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0; Data Source='excel_file\\events2.xlsx'; " +
"Extended Properties=\"Excel 12.0 Xml;HDR=YES;\"");
try
{
//SQL STATEMENT TO SAVE INSERTED BY THE USER VALUES FROM THE TEXT BOXES
//SQL1 STATEMENT TO GENERATE EVENTID NUMBER EACH TIME THE USER SAVES NEW ROW OF DATA
MyConnection.Open();
myCommand.Connection = MyConnection;
sql = "Insert into [events$] (EventID,EventName, Type, Name, [Value], Description) values(#EventID,#EventName,#Type,#Name,#Val,#Desc)";
myCommand.CommandText = sql;
myCommand.Parameters.AddWithValue("#EventID",sql1);
myCommand.Parameters.AddWithValue("#EventName", eventName ?? DBNull.Value);
myCommand.Parameters.AddWithValue("#Type", typeValue ?? DBNull.Value);
myCommand.Parameters.AddWithValue("#Name", nameValue ?? DBNull.Value);
myCommand.Parameters.AddWithValue("#Val", attribvValue ?? DBNull.Value);
myCommand.Parameters.AddWithValue("#Desc", descValue ?? DBNull.Value);
myCommand1.Connection = MyConnection;
sql1= "DECLARE #i int = 0 while #i < EventID BEGIN SET #i = EventID + 1 END";
myCommand1.CommandText = sql1;
myCommand.ExecuteNonQuery();
myCommand1.ExecuteNonQuery();
MyConnection.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
finally
{
MyConnection.Close();
Events eventsWindow = new Events();
eventsWindow.dgData.Items.Refresh();
}
}
Since your command is running before command1 sql1 = null, That is what your problem is.
You need to set the value of sql1 before executing the command. If you really want the value to be null you need to use DBNull.Value as you have for the other parameters.

Local AppData Monitor in Metro app (StorageFileQueryResult.ContentsChanged event not firing)

how would a monitor just a particular file in AppData folder.
I've tried using StorageFolderQueryResult.ContentsChanged event to handle this, but this one actually callbacks for any changes through the folder.
My problem is to just a monitor a single file and use the eventhandler when its changed.
I've tried to use this "UserSearchFilter" property to QueryOptions. That didnt work actually.
cAn someone help with this ? It would also be helpful if you could additionally provide the syntax for the whole problem.
My contentschanged event is not firing on modifying the "filename" in the folder.
auto fileTypeFilter = ref new Platform::Collections::Vector<Platform::String^>();
fileTypeFilter->Append("*");
auto queryOptions = ref new QueryOptions(CommonFileQuery::OrderBySearchRank, fileTypeFilter);
//use the user's input to make a query
queryOptions->UserSearchFilter = InputTextBox->Text;
auto queryResult = musicFolder->CreateFileQueryWithOptions(queryOptions);
auto localFolder = ApplicationData::Current->LocalFolder;
auto currPath = localFolder->Path;
auto fileTypeFilter = ref new Platform::Collections::Vector<Platform::String^>();
fileTypeFilter->Append(".dat");
auto queryOptions = ref new QueryOptions(CommonFileQuery::OrderByName, fileTypeFilter);
//use the user's input to make a query
queryOptions->UserSearchFilter = L"filename";
auto queryResult = localFolder->CreateFileQueryWithOptions(queryOptions);
queryResult->ContentsChanged += ref new TypedEventHandler<IStorageQueryResultBase^, Platform::Object^>(this, &Scenario1::OnLocalAppDataChanged);
//find all files that match the query
create_task(queryResult->GetFilesAsync()).then([this, queryOptions] (IVectorView<StorageFile^>^ files)
{
String^ outputText = "";
//output how many files that match the query were found
if ( files->Size == 0)
{
outputText += "No files found for '" + queryOptions->UserSearchFilter + "'";
}
else if (files->Size == 1)
{
outputText += files->Size.ToString() + " file found:\n\n";
}
else
{
outputText += files->Size.ToString() + " files found:\n\n";
}
//output the name of each file that matches the query
for (unsigned int i = 0; i < files->Size; i++)
{
outputText += files->GetAt(i)->Name + "\n";
}
OutputTextBlock->Text = outputText;
});
}
void Scenario1::OnLocalAppDataChanged(Windows::Storage::Search::IStorageQueryResultBase^ sender, Platform::Object^ args)
{
Platform::String^ hello = L"hello world, I'm called back";
}
You have to call the method GetFilesAsync() at least once, otherwise the event will never fire.
Add
queryResult->GetFilesAsync();
before
queryResult->ContentsChanged += ref new TypedEventHandler<IStorageQueryResultBase^,...
I know you don't really need the files at that point, but that's the offical way the ContentsChanged event should be used. Have a look at the first paragraph of the documentation.

How to save image to the database after it is scanned

I have developed a windows application to scan images.After the image is scanned i want to save it directly to the database not in local machine...The code which i have used is as follows
try
{
String str = string.Empty;
WIA.CommonDialogClass scanner;
ImageFile imageObject;
scanner = new CommonDialogClass();
imageObject = scanner.ShowAcquireImage
(WiaDeviceType.ScannerDeviceType,
WiaImageIntent.ColorIntent,
WiaImageBias.MinimizeSize,
ImageFormat.Jpeg.Guid.ToString("B"),
false,
true,
true);
str = DateTime.Now.ToString();
str = str.Replace("/", "");
str = str.Replace(":", "");
Directory.CreateDirectory("D:\\scanned1");
// MessageBox.Show(string.Format("File Extension = {0}\n
//\nFormat = {1}", imageObject.FileExtension, imageObject.FormatID));
imageObject.SaveFile(#"D:\scanned1\lel" + str + ".jpg");
MessageBox.Show("Scanning Done");
}
catch (Exception ex)
{
MessageBox.Show("Please check if the scanner is connected properly.");
}
Instead of saving it to D drive i want to save it to database.....How can i do it?Plz reply...
I've got no idea what "ImageFile" is really, but there should be a way to transform it into the byte array (byte[]). Afterwards you would need to insert that array to varbinary field in your sql.
something like this:
using(SqlCommand cmd = new SqlCommand("INSERT INTO MyTable (myvarbinarycolumn) VALUES (#myvarbinaryvalue)", conn))
{
cmd.Parameters.Add("#myvarbinaryvalue", SqlDbType.VarBinary, myarray.length).Value = myarray;
cmd.ExecuteNonQuery();
}
ofc sqlcommand should be opened and valid.
myarray is of type byte[]

Rollback INSERT Command in C#.NET

I had some confusion which I want to clear it - I am inserting values into database using ADO.NET. Let say I want to insert 10 item if I encounter error while inserting data of 5th item it should roll back whatever I had inserted into the database.
I just read the concept of Transaction and Rollback method and also tried to implement it in the program but still it insert 4 item and give me error message of 5th item. It doesn't roll back insert query.
Does transaction and roll back method solved my issue or I need to used other alternative.
here is my code,
for (int i = 0; i < itemLength - 1; i++)
{
//--- Start local transaction ---
myTrans = Class1.conn.BeginTransaction();
//--- Assign transaction object and connection to command object for a pending local transaction ---
_insertQry = Class1.conn.CreateCommand();
_insertQry.Connection = Class1.conn;
_insertQry.Transaction = myTrans;
_insertQry.CommandText = "INSERT INTO Product_PropertyValue(ItemNo, PropertyNo, ValueNo) VALUES (#ItemNo, #PropertyNo, #ValueNo)";
//_insertQry = new SqlCommand("INSERT INTO Product_PropertyValue(ItemNo, PropertyNo, ValueNo) VALUES (#ItemNo, #PropertyNo, #ValueNo)", Class1.conn);
_insertQry.Parameters.AddWithValue("#ItemNo", _itemNo[i]);
_insertQry.Parameters.AddWithValue("#PropertyNo", _propNo);
_insertQry.Parameters.AddWithValue("#ValueNo", _propValue);
_insertQry.ExecuteNonQuery();
myTrans.Commit();
}
Can anyone help me?
It sounds like you are trying to achieve an atomic commit. It either inserts completely or doesn't insert at all.
Try something like the following
SqlTransaction objTrans = null;
using (SqlConnection objConn = new SqlConnection(strConnString))
{
objConn.Open();
objTrans = objConn.BeginTransaction();
SqlCommand objCmd1 = new SqlCommand("insert into tbExample values(1)", objConn);
SqlCommand objCmd2 = new SqlCommand("insert into tbExample values(2)", objConn);
try
{
objCmd1.ExecuteNonQuery();
objCmd2.ExecuteNonQuery();
objTrans.Commit();
}
catch (Exception)
{
objTrans.Rollback();
}
finally
{
objConn.Close();
}
Also take a look at
http://www.codeproject.com/Articles/10223/Using-Transactions-in-ADO-NET
I did 2 modification to your code
1) Move the BeginTransaction() outside the for loop, So that all your 10 INSERt statements are in a single transaction, that is what you want if you want them to be atomic
2) added a TRY/CATCH block, so that you can roll back in case of errors.
//--- Start local transaction ---
myTrans = Class1.conn.BeginTransaction();
bool success = true;
try
{
for (int i = 0; i < itemLength - 1; i++)
{
//--- Assign transaction object and connection to command object for a pending local transaction ---
_insertQry = Class1.conn.CreateCommand();
_insertQry.Connection = Class1.conn;
_insertQry.Transaction = myTrans;
_insertQry.CommandText = "INSERT INTO Product_PropertyValue(ItemNo, PropertyNo, ValueNo) VALUES (#ItemNo, #PropertyNo, #ValueNo)";
//_insertQry = new SqlCommand("INSERT INTO Product_PropertyValue(ItemNo, PropertyNo, ValueNo) VALUES (#ItemNo, #PropertyNo, #ValueNo)", Class1.conn);
_insertQry.Parameters.AddWithValue("#ItemNo", _itemNo[i]);
_insertQry.Parameters.AddWithValue("#PropertyNo", _propNo);
_insertQry.Parameters.AddWithValue("#ValueNo", _propValue);
_insertQry.ExecuteNonQuery();
}
}
catch (Exception ex)
{
success = false;
myTrans.Rollback();
}
if (success)
{
myTrans.Commit();
}
let me know if this doesn't works.
You are on the right path, ADO.NET supports transactions so you will be able to rollback on errors.
Posting your your code here would get you more specific guidance; However since your question is very generic, I will encourage you to follow the template provided by MSDN
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
// Start a local transaction.
SqlTransaction sqlTran = connection.BeginTransaction();
// Enlist a command in the current transaction.
SqlCommand command = connection.CreateCommand();
command.Transaction = sqlTran;
try
{
// Execute two separate commands.
command.CommandText =
"INSERT INTO Production.ScrapReason(Name) VALUES('Wrong size')";
command.ExecuteNonQuery();
command.CommandText =
"INSERT INTO Production.ScrapReason(Name) VALUES('Wrong color')";
command.ExecuteNonQuery();
// Commit the transaction.
sqlTran.Commit();
Console.WriteLine("Both records were written to database.");
}
catch (Exception ex)
{
// Handle the exception if the transaction fails to commit.
Console.WriteLine(ex.Message);
try
{
// Attempt to roll back the transaction.
sqlTran.Rollback();
}
catch (Exception exRollback)
{
// Throws an InvalidOperationException if the connection
// is closed or the transaction has already been rolled
// back on the server.
Console.WriteLine(exRollback.Message);
}
}
}

Resources