The file 'C:\....\.....\.....\bin\debug\128849991926295643' already exists - database

I'm using Visual C#2008 Express Edition and an Express SQL database. Every time I build my solution, I get an error like the one above. Obviously the file name changes. A new file is also created every time I hit a debug point.
I have a stored proc that gets every row from a database table, it gets these rows every time the main form initialises and Adds them to a Generics list. Without inserting or deleting from the table, it gets a different number of rows each time I start my windows application. The error started happening at the same time as the weird data retrieval issue. Any ideas at all about what can cause this?
Thanks
Jose,
Sure, here's my c# method, it retrieves every row in my table, each row has an int and and Image ....
private List<ImageNumber> GetListOfKnownImagesAndNumbers()
{
//ImageNumber imNum = new ImageNumber();
SqlCommand sqlCommand = new SqlCommand();
sqlCommand.Connection = _conn;
try
{
MemoryStream ms = new MemoryStream();
sqlCommand.CommandText = "usp_GetKnownImagesAndValues";
_conn.Open();
using (IDataReader dr = sqlCommand.ExecuteReader())
{
while (dr.Read())
{
ImageNumber imNum = new ImageNumber();
imNum.Value = dr.IsDBNull(dr.GetOrdinal("ImageValue")) ? 0 : Convert.ToInt32(dr["ImageValue"]);
//Turn the bitmap into a byte array
byte[] barrImg = (byte[])dr["ImageCaptured"];
string strfn = Convert.ToString(DateTime.Now.ToFileTime());
FileStream fs = new FileStream(strfn,
FileMode.CreateNew, FileAccess.Write);
fs.Write(barrImg, 0, barrImg.Length);
fs.Flush();
fs.Close();
imNum.Image = (Bitmap)Image.FromFile(strfn);
_listOfNumbers.Add(imNum);
}
dr.Close();
_conn.Close();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
_conn.Close();
}
return _listOfNumbers;
}
And here's my stored proc....
ALTER PROCEDURE dbo.usp_GetKnownImagesAndValues
AS
BEGIN
select ImageCaptured, ImageValue
from CapturedImages
END

Thanks for looking at this. The answer in the end was to put a Thread.Sleep inside the while loop and it started working perfectly. There may be something else I could do, I am obviously waiting for something to complete which is why allowing more time has helped here. If I knew what needed to complete and how to detect when it had completed then I could check for that instead of simply waiting for a short time.

Related

Updating Database Value in windows forms

I am trying to do a function to update a value in a SQL database, this is my table
This is the function
private void UpdateGanToDB(float entrada, string Id)
{
string string_entrada = entrada.ToString();
string conString = Properties.Settings.Default.LocalDataBaseConnectionString;
string command_string = "UPDATE Gan SET Ganan = #GetGan WHERE Id = #GetId";
SqlConnection connection = new SqlConnection(conString);
SqlCommand cmd = new SqlCommand(command_string, connection);
cmd.Parameters.AddWithValue("#GetGan", string_entrada);
cmd.Parameters.AddWithValue("#GetId", Id);
try
{
connection.Open();
int row = cmd.ExecuteNonQuery();
if (row > 0) {
MessageBox.Show("Upgrade successful");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
connection.Close();
}
}
I am getting the message "upgrade successful" but when I check the database I can't see the changes. When I run the text in the command_string with known values I can see the changes but not with my function
Edit:
I added this code to the code above
int row = cmd.ExecuteNonQuery();
if (row > 0) {
SqlCommand command = new SqlCommand("SELECT * FROM Gan ", connection);
SqlDataAdapter adapter = new SqlDataAdapter(command);
System.Data.DataTable dataTable = new System.Data.DataTable();
adapter.Fill(dataTable);
MessageBox.Show(dataTable.Rows[0]["Ganan"].ToString());
}
To see if it is updating the value and I get the excepted 200 (Original value was 0) But When I close the application and see the values in the local database I see the original value 0 I don't know why the update is not saving
EDIT2:
I found another post with a work around for this problem: Can I commit changes to actual database while debugging C# in Visual Studio?
I think your code is correct and there is no problem
If you created database via Add\NewItem\Service-Base Database
I'm not sure, but I think After running your project, one copy of your original database will be included in the debug folder in your project and the update operation and also other operations run on that, not your original database
so, if you want to see a result, you should connect to that via View\ServerExplorer
meantime, after Change your Code and rebuild your Project, your debug database will be deleted and again one copy of your original database will be included in the debug folder

Send all records from SQL Server table though send mail task in body

I am trying to send all the table records in email body though send mail task
My flow:
I uses SQL execute task to fetch the rows from table and stored in an object
Uses for each loop container and in that I use a script task to store the rows in an EmailMessage body
I used Send mail task to send the email
I am only getting last records of the table in the message body.
Please guide me how to send all the table data at once in a message body
Actaul flow
error
I think I would take a slightly different approach and recurse the recordset directly in the script task but this looks like it would work too. I would guess that your problem is that you overwrite User::EmailMessage at every iteration. You say you get last few records but looking at your code I would think you will get 1 unless you uncomment the IF (varcollection == string.empty) in which case you might get more.
Anyway, the main offending problem is
varCollection["User::EmailMessage"].Value = header;
That resets your EmailMessage body to the header row any time it is called.
Edit: Adding as per your comment to reset message at every new shipment number. Add another package variable PrevShippingNum which will hold the previous looped number to test if it is the same or has changed. Make sure that this variable is listed as ReadWriteVariable to the script task. then modify your script to include something like this:
Dts.VariableDispenser.GetVariables(ref varCollection);
bool newMessage = (varCollection["User::PrevShippingNum"].value != varCollection["User::ShppingNum"].value) ? true : false;
if (string.IsNullOrWhiteSpace(varCollection["User::EmailMessage"].Value.ToString()) || newMessage)
{
varCollection["User::EmailMessage"].Value = string.Format("{0}........");
}
varCollection["User::EmailMessage"].Value += string.Format("{0}......");
The positive about this is you can also use your new variable as a constraint to determine when to send email task.
A different Approach:
Note pretty big edit to add new sub to take care of sending emails per ShippingNum:
Way I would proceed pass the recordset variable you are using to a script task and let it do the email message building. Just to be clear this is to replace your foreach loop! here is some code adapted from one of my solutions:
Add Reference to System.Data.DataSetExtensions
Add following namespaces:
using System.Data.OleDb;
using System.Net.Mail;
using System.Linq;
using System.Collections.Generic;
private void Main()
{
//using System.Data.OleDb;
OleDbDataAdapter oleAdapter = new OleDbDataAdapter();
DataTable dt = new DataTable();
oleAdapter.Fill(dt, Dts.Variables["User::OleDbRecordSetVar"].Value);
//build header row
string headerRow = string.Format("{0}........", "ShippingNum ....");
//get distinct shippingNums
var shippingNums = (from DataRow dr in dt.Rows
select (int)dr["ShppingNum"]).Distinct();
//Now Build the Differnt Emails
foreach (var num in shippingNums)
{
string emailBody = headerRow;
List<DataRow> emailLines = (from DataRow dr in dt.Rows
where (int)dr["ShippingNum"] == num
select dr).ToList<DataRow>();
foreach (DataRow line in emailLines)
{
emailBody += string.Format("{0}....", line["ColumnName1"].ToString(), line["ColumnName2"].ToString());
}
SendEmail(emailBody);
}
Dts.TaskResult = (int)ScriptResults.Success;
}
private void SendEmail(string messageBody)
{
//get the smtp server address from the SSIS connection manger
ConnectionManager smtpConnectionManager = Dts.Connections["Name Of SMTP Connection Manager"];
//note this is for trusted authentication if you want to use a username and password you will have to do some discovery
SmtpClient emailClient = new SmtpClient(smtpConnectionManager.Properties["SmtpServer"].GetValue(smtpConnectionManager).ToString());
MailMessage email = new MailMessage();
email.Priority = MailPriority.Normal;
email.IsBodyHtml = false; //change to true if you send html
//can hard code addresses if you desire I use variables to make it more flexible
email.From = new MailAddress(Dts.Variables["User::FromAddress"].Value.ToString());
email.To.Add(Dts.Variables["User::ToAddress"].Value.ToString());
email.Body = messageBody;
emailClient.Send(email);
}

Check MySql Connection is Opened Or Not in Visual C++

Sorry, If u filling bored. I have searched on several search engines but could not got any result. Anyway I am working in an App which database is mysql. Now I have created a database wrapper class and want to check if the connection is already opened. Could u help me?
String^ constring = L"datasource=localhost;port=3306;username=root;password=pass;database=eps;";
String^ my_query = L"select id from eps_users where usr = '" + this->user_name->Text + "' and psw = md5('" + this->pass_word->Text + "');";
MySqlConnection^ conDatabase = gcnew MySqlConnection(constring);
MySqlCommand^ cmd = gcnew MySqlCommand(my_query, conDatabase);
MySqlDataReader^ myreader;
try
{
conDatabase->Open();
myreader = cmd->ExecuteReader();
int count = 0;
while (myreader->Read())
{
count = count + 1;
}
if (count == 1){
MessageBox::Show("Username And Password is correct.", "Success", MessageBoxButtons::OK,
MessageBoxIcon::Information);
this->Hide();
Form2^ f2 = gcnew Form2(constring);
f2->ShowDialog();
}
else{
MessageBox::Show("Username And Password is not correct.", "Error", MessageBoxButtons::OK,
MessageBoxIcon::Error);
// <del>
this->Hide();
Form2^ f2 = gcnew Form2(constring);
f2->ShowDialog();
// </del>
}
}
catch (Exception^ ex)
{
MessageBox::Show(ex->Message);
}
conDatabase->Close();
I need to check if( conDatabase->HasBeenOpened()) { conDatabase->Open();}
The MySqlConnection type implements a feature called connection pooling that relies on the garbage collector to help recycle connections to your database, such that the best practice with regards to connection objects is to create a brand new object for most calls to the database, so that the garbage collector can correctly recycle the old ones. The process goes like this:
Create a new connection
Open the connection
Use the connection for one query/transaction
Dispose the connection
Where all four steps live within a single try/catch/finally block. (Also, the dispose step needs to happen inside the finally block!) Because you generally start with a brand new connection object, there's not typically a need to check if it's open first: you know it's closed. You also don't need to check the state after calling Open(): the method will block until it's finished, and throw an exception if it fails.
However, if you really are in one of the (rare!) situations where it's a good idea to preserve the connection for an extended period, you can check the state like this:
if( conDatabase->State == ConnectionState::Open)
Now, there is one other issue in that code I'd like to talk about. The issue comes down to this: what do you think will happen if I put the following into your username text box:
';DROP Table eps_users;--
If you think that it will try to execute that DROP statement in your database, you're right: it will! More subtle and damaging queries are possible, as well. This is a huge issue: there are bots that run full time crawling web sites looking for ways to abuse this, and even an corporate internal desktop apps will get caught from time to time. To fix this, you need to use Parameterized Queries for every instance where include user-provided data as part of your sql statement.
A quick example might look like this:
String^ my_query = L"select id from eps_users where usr = #userID;";
MySqlCommand^ cmd = gcnew MySqlCommand(my_query, conDatabase);
cmd->Parameters->AddWithValue(L"#userID", this->user_name->Text);

Blackberry - Cant see always db in sd card emulator

I dont know what's happenning.
This is my code:
public class MyApp extends MainScreen {
Database sqliteDB;
URI uri;
String name;
public MyApp()
{
try{
uri = URI.create("file:///SDCard/Databases/sample/" +"prueba.db");
sqliteDB = DatabaseFactory.create(uri);
sqliteDB = DatabaseFactory.open(uri);
Statement st = sqliteDB.createStatement("CREATE TABLE joke(name)");
st.prepare();
st.execute();
st.close();
Statement st1 = sqliteDB.createStatement("INSERT INTO joke VALUES ('Maxo')");
st1.prepare();
st1.execute();
st1.close();
Statement st2 = sqliteDB.createStatement("INSERT INTO joke VALUES ('Lala')");
st2.prepare();
st2.execute();
st2.close();
/*
Statement st1 = sqliteDB.createStatement("SELECT * from joke");
st1.prepare();
Cursor c = st1.getCursor();
Row r;
while(c.next()) {
r = c.getRow();
name = r.getString(0);
}
st1.execute();
st1.close();*/
sqliteDB.close();
add(new RichTextField("Status: Database was created and inserted the values successfully"));
//add(new RichTextField(""+name));
}
catch (Exception e){
System.out.println(e.getMessage());
e.printStackTrace();
}
}
}
Im just creating a database, a table and inserting two fields. So what i do is first execute emulator, set a directory to my sdcard. Well after that i execute my program, and sometimes it creates the database in that directoy, sometimes not, sometimes it creates database without table or data.. i dont know why, i tried 8520 9550 emulator, but its rare whats happenning with database and sdcard. Anyone has an idea of what could be happenning? Its annoying to be coding and sometimes it works sometimes not and you dont know why.. And its not coding problem i think, because sometimes it works :S
Make sure u have mounted your SD card.Double click on the folder where you want to save your database and then tick the checkbox for remounting it on next emulator run.
Hope it helps.

SSIS : big load and outofmemory exception

I'm currently working with Integration Services (SSIS) to load a big amount of XML files into a SQL server database. Each XML file content needs to be dispatched in several tables. I have at least 10000 xml files to load using the process. Everything works fine till 6000 files are loaded. After 6000 treatment, I always got an OutOfMemoryException from my first dataflow task, the first in the process.
In this script component, I just check if a value from a XML file is already present in a specific database table. If it is present, I return the matched ID, otherwise, I add a new record. To achieve it, I use a Lookup component. I use it with No cache option, for memory matter. Then in case of matching, I process the return ID in a script component. Like I said, everything works fine until more or less 6000 files are processed. After I got :
Description : System.OutOfMemoryException: Exception of type 'System.OutOfMemoryException' was thrown.
at Microsoft.SqlServer.Dts.Pipeline.ScriptComponentHost.HandleUserException(Exception e)
at Microsoft.SqlServer.Dts.Pipeline.ScriptComponentHost.PreExecute()
at Microsoft.SqlServer.Dts.Pipeline.ManagedComponentHost.HostPreExecute(IDTSManagedComponentWrapper100 wrapper)
Do you have some suggestions or some ressources which deal with performance and memory issue in SSIS ? Do you encountered similar problem ? DO you have an idea from where this memory problem could come from?
Thanks :)
EDIT:
Here is the code to check an XML against an XSD file. Can you see any memory leak?
public void Main()
{
try
{
XmlReaderSettings settings = new XmlReaderSettings();
settings.Schemas.Add("", Dts.Variables["XSDFilePath"].Value.ToString());
settings.ValidationType = ValidationType.Schema;
using (XmlReader reader = XmlReader.Create(Dts.Variables["XMLFilePath"].Value.ToString(), settings))
{
XmlDocument document = new XmlDocument();
document.Load(reader);
ValidationEventHandler eventHandler = new ValidationEventHandler(XMLValidationHandler);
document.Validate(eventHandler);
}
if (ValidationResult)
{
Dts.TaskResult = (int)ScriptResults.Success;
}
else
{
Dts.TaskResult = (int)ScriptResults.Failure;
}
}
catch (Exception ex)
{
Dts.TaskResult = (int)ScriptResults.Failure;
}
}
private void XMLValidationHandler(object sender, ValidationEventArgs e)
{
switch (e.Severity)
{
case XmlSeverityType.Error:
Console.WriteLine("Warning {0}", e.Message);
ValidationResult = false;
break;
case XmlSeverityType.Warning:
Console.WriteLine("Warning {0}", e.Message);
break;
}
}
Don't use the XMLDocument Object, It will load the entire document into memory and is likely the cause of your memory problem. Try instead to use the XmlValidatingReader
http://msdn.microsoft.com/en-us/library/system.xml.xmlvalidatingreader.aspx
It should provide a more efficient use of memory.
Refer to the 'answers' in this.,
http://social.msdn.microsoft.com/Forums/en-US/sqlintegrationservices/thread/4d90afc8-0a1c-418f-9e3a-0b766f581b2c/

Resources