|
the content of connection string is a access database file that i don't want to locally connect with my c# because it is updated every time and user can import to the program with reference year the records that associated with this year i try to make it locally connected in c# and i observe that the database does not updated when i make it import again from my desktop on my laptop so the database that it is locally connected to my c# program has old record in spite of the two file it is the same but on different locations (locally- desktop and the other can be import to c#) .
i use the following query to get the records with the associated reference year but i have the problem that i said previous :
public DataTable findref2(string refyear)
{
try
{
//create new new connection to the database
OleDbConnection conn = new OleDbConnection(connectionstringA);
//Set the command string
string Cmd = ("SELECT ReferenceYear FROM Questionnaires_Table1 Where ReferenceYear = '" + refyear + "' ");
//create new data adapter
OleDbDataAdapter Adapter = new OleDbDataAdapter(Cmd, conn);
//create new command builder
OleDbCommandBuilder sqlCmdBuilder = new OleDbCommandBuilder(Adapter);
dTable = new DataTable();
Adapter.Fill(dTable);
conn.Close();
}
catch (OleDbException e)
{
MessageBox.Show(e.ToString());
}
//return the search results on a datatable
return dTable;
}
how can i get data without make my database locally connected in my c# program and i have the possibility to get data when i import from anywhere on my laptop to c# program. i have already a form that i put the reference year and opened a window that i can choose the access db file and i can import to my c# program (because i move on my locally connected access database which is different from database i make import ) but only if the year i put previous is on access db file i choose. Now i try to make a select query to check if the reference year already exists on file but i have the error No database specified in connection string or IN clause maybe because i must make locally connection on c# but i don't want as i said previous.
can you help me please?
modified 7-Jul-13 15:31pm.
|
|
|
|
|
I'm not sure that I understand completely but it sounds as if you are trying to access a database file by copying it from one location to another before extracting or updating its records. You would be better using a database system that you can access remotely, like SQL Server.
zebra88 wrote: but i have the error No database specified in connection string or IN clause And again I would ask, what is the actual content of your connection string? Using your debugger would help you diagnose this problem much faster than posting questions here.
Use the best guess
|
|
|
|
|
Hello,
I am currently creating an application that connects to a SQL database with approximately 800 rows.
The database is currently taking approximately 30 seconds to return any data when I run any sort of SELECT query. I was wondering if anyone had any ideas as to why?
Here is an example:
fillDataGrid("SELECT UID, SiteName, DateConnected FROM tblSites ORDER BY DateConnected ASC");
private void fillDataGrid(string query)
{
try
{
_DataAdapter = new SqlDataAdapter(query, _SQLConnection);
_DataTable = new DataTable();
_SQLConnection.Open();
_DataAdapter.Fill(_DataTable);
_SQLConnection.Close();
dataGrid.DataSource = _DataTable;
}
catch
{
}
|
|
|
|
|
How long does it take on management studio ?
|
|
|
|
|
How long does the same query take to run on the database directly? I have a feeling that it could be index related.
Every day, thousands of innocent plants are killed by vegetarians.
Help end the violence EAT BACON
|
|
|
|
|
As with any sql query issue you should test the query in SSMS (SQL Server Management Studio), turn on the Actual Action Plan and run the query. Look for the high cost nodes and deal with those issues.
Never underestimate the power of human stupidity
RAH
|
|
|
|
|
I'm getting the folloiwng error:
A callback was made on a garbage collected delegate of type 'OPC_Library!OPC_Library.OPC_DLL+WriteNotificationDelegate::Invoke'. This may cause application crashes, corruption and data loss. When passing delegates to unmanaged code, they must be kept alive by the managed application until it is guaranteed that they will never be called.
I m creating an opc server,I have a form opcSrvr & a .cs file called TcpCommServer,
my code is here:
opcSrvr.cs
OPC_DLL.WriteNotificationDelegate writeCallBack;
public static TcpCommServer.ServerCallbackDelegate del;
TcpCommServer _Server;
public opcSrvr()
{
InitializeComponent();
writeCallBack = new OPC_DLL.WriteNotificationDelegate(myWriteCallBack);
del += new Airsprint_OPCServer.TcpCommServer.ServerCallbackDelegate(UpdateUI);
_Server = new Airsprint_OPCServer.TcpCommServer(del);
}
public void UpdateUI(byte[] bytes, Int32 sessionID, int dataChannel)
{
if (this.InvokeRequired)
{
this.Invoke(_Server.ServerCallbackObject, bytes, sessionID, dataChannel);
}
else
{
// the usual stuff
}
}
public void myWriteCallBack(UInt32 hItem, ref Object Value, ref UInt32 ResultCode)
{
ResultCode = 0;
try
{
ResultCode = 0;
if (hItem == TagHandle[0])
{
textBox1.Text = Convert.ToString (Value);
OPC_DLL.UpdateTag.UpdateTag(TagHandle[0], textBox1.Text, 192);
}
if (hItem == TagHandle[1])
{
textBox2.Text = Convert.ToString(Value);
OPC_DLL.UpdateTag.UpdateTag(TagHandle[1], textBox2.Text, 192);
}
if (hItem == TagHandle[2])
{
textBox3.Text = Convert.ToString(Value);
OPC_DLL.UpdateTag.UpdateTag(TagHandle[2], textBox3.Text, 192);
}
if (hItem == TagHandle[3])
{
textBox4.Text = Convert.ToString(Value);
OPC_DLL.UpdateTag.UpdateTag(TagHandle[3], textBox4.Text, 192);
}
}
catch(Exception ex)
{
}
}
private void opcSrvr_Load(object sender, EventArgs e)
{
OPC_DLL.InitWTOPCsvr("{638A1D6E-D7CD-45F4-98E7-ADEB72218DA3}", 1000);
OPC_DLL.EnableWriteNotification(myWriteCallBack, true);
TagHandle[0] = OPC_DLL.CreateTag("Tag.1", textBox1.Text, 192, true);
TagHandle[1] = OPC_DLL.CreateTag("Tag.2", textBox2.Text, 192, true);
TagHandle[2] = OPC_DLL.CreateTag("Tag.3", textBox3.Text, 192, true);
TagHandle[3] = OPC_DLL.CreateTag("Tag.4", textBox4.Text, 192, true);
}
opc.dll is the file which contain all required dll's. its a multithreading programming.can you tell me how to fix this error? am i doing any mistake in initialization? plz help me!!!
|
|
|
|
|
Does this happen when the OPC server is closed, or the application exits? You should properly implement IDisposable on your OPC type so that you can release the event handlers correctly. This requires you to implement a Dispose() method where you can release the server callback delegates.
What is probably happening is that the server isn't referenced anymore so the garbage collector picks it up and collects it, but since the OPC server still has active delegates it tries to call them on a disposed object. You need to release the OPC COM objects and un-initialize the OPC server when the server gets garbage collected.
|
|
|
|
|
It looks like you knew what you were supposed to do but then forgot to do it.
In the constructor you have explicitly created a delegate and assigned it to the field writeCallBack so that it will not be garbage collected. But in the opcSrvr_Load method there is implicit delegate creation in the line
OPC_DLL.EnableWriteNotification(myWriteCallBack, true);
Should that be
OPC_DLL.EnableWriteNotification(this.writeCallBack, true);
Alan.
|
|
|
|
|
Good catch, still needs to implement proper disposal methods though when working with COM objects like OPC servers
|
|
|
|
|
The question is given. Which one's faster? I would think the second one, but I am not sure.
|
|
|
|
|
This SO post may help you[^] - However I doubt if list.First() does anything else than
return list[0];
so list[0] may be marginally faster. As explained in the post, the main difference is the kind of Exception you get when no element is in the list.
cheers,
Marco
|
|
|
|
|
if you can call
var item = list[0]
it's probably faster than calling
var item = list.First()
This is the code of the First Extension
public static TSource First<TSource>(this IEnumerable<TSource> source) {
if (source == null) throw Error.ArgumentNull("source");
IList<TSource> list = source as IList<TSource>;
if (list != null) {
if (list.Count > 0) return list[0];
}
else {
using (IEnumerator<TSource> e = source.GetEnumerator()) {
if (e.MoveNext()) return e.Current;
}
}
throw Error.NoElements();
}
The First method is a LINQ-Extension and is used for IEnumerable. Not all IEnumberable implementations do support the direct access of elements through an index (As IEnumberable does not have a method implemented for it).
IEnumberable gets implemented by nearly all of the .NET Collections, Lists or Arrays. So you don't have to care if you can access it directly with the index or not.
|
|
|
|
|
Directly accessing the element is faster, if there are elements in the list. However, what about if there are no elements? What happens then? Of course, both cases would result in an exception, which is where the oddity comes into play that is, at this point it's probably faster to call FirstOrDefault if the list can be null. Of course, where things get interesting is the fact that list[0] might contain a value, but it might not be the one that you're interested in, because First is designed to work as a Linq expression, so it can return you the item that is at a certain location based on the results of your Linq query.
|
|
|
|
|
LINQ is quicker to write but not necessarily always faster.
|
|
|
|
|
HI ,
even after inserting different patient id on windows form and when clicked save button.
I am getting an Error :
<pre lang="css">An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll
Additional information: Violation of PRIMARY KEY constraint 'pk_patienid'. Cannot insert duplicate key in object 'dbo.patient'.
The statement has been terminated.</pre>
even after inserting different patient id on windows form and when clicked save button.
my code is :
private void button1_Click(object sender, EventArgs e)
{
resetLabels();
using (SqlConnection cn = new SqlConnection())
{
cn.ConnectionString = @"Data Source=.\SQLEXPRESS;AttachDbFilename=Q:\Dotnet\dental1\dental1\patientdb.mdf;Integrated Security=True;User Instance=True";
cn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = cn;
cmd.CommandText = "select convert(varchar(50),getdate(),105) as date";
SqlDataReader sdr = cmd.ExecuteReader();
while (sdr.Read())
{
date = sdr["date"].ToString();
}
sdr.Close();
setPatientidtxt();
if (updateflag)
{
cmd.CommandText = "update Patient set" +
" name=@FirstName,surname=@LastName,age=@Age,city=@City,gender=@Gender,allergy=@Allergy,phoneno=@ContactNo,consultingfees=@Fees,note=@Note,date=@Date,time=@Time" +
" where patientid=@Patientid";
cmd.Parameters.AddWithValue("@Patientid", Convert.ToInt64(textBox1.Text));
}
else
{
cmd.CommandText = "insert into patient (patientid,name,surname,age,city,gender,allergy,phoneno,consultingfees,note,date,time) values" +
"(@patientid,@FirstName,@LastName,@Age,@City,@Gender,@Allergy,@ContactNo,@Fees,@Note,@Date,@Time)";
}
cmd.Parameters.AddWithValue("@patientid", textBox1.Text);
cmd.Parameters.AddWithValue("@FirstName", textBox2.Text);
cmd.Parameters.AddWithValue("@LastName", textBox3.Text);
cmd.Parameters.AddWithValue("@Age", textBox4.Text);
cmd.Parameters.AddWithValue("@City", textBox5.Text);
//radio button
if (radioButton1.Checked == true)
{
cmd.Parameters.AddWithValue("@Gender", radioButton1.Text);
}
else
{
cmd.Parameters.AddWithValue("@Gender", radioButton2.Text);
}
if (radioButton3.Checked == true)
{
cmd.Parameters.AddWithValue("@Allergy", radioButton3.Text);
}
else
{
cmd.Parameters.AddWithValue("@Allergy", radioButton4.Text);
}
cmd.Parameters.AddWithValue("@ContactNo", textBox6.Text);
cmd.Parameters.AddWithValue("@Fees", textBox7.Text);
cmd.Parameters.AddWithValue("@Note", textBox8.Text);
cmd.Parameters.AddWithValue("@Date", System.DateTime.Now.ToShortDateString());
cmd.Parameters.AddWithValue("@Time", System.DateTime.Now.ToLongTimeString());
cmd.ExecuteNonQuery();
button4.Enabled = true;
label11.Visible = true;
label4.Visible = true;
timer1.Start();
}
}
only first time data is saved in database: and ome colums as 0
patientid name surname age city gender allergy phone no consultationfes date time
0 0 Male No 0 0 07-05-2013 00:23:06
NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL
|
|
|
|
|
So, I take it that patientid is the primary key here. I also bet you haven't set it up to be an auto incrementing number (an identity column). Open the table up in SQL Server Manager, click on the column and check the properties on that column. Set it to be identity. Finally, amend your insert query so that it doesn't attempt to pass in a patientid - if it's auto incrementing, you don't need to specify the column when you enter it.
Now, when you enter code, use the pre block to mark the code only. So, to get this:
public void DoSomething(int counter)
{
} Your message would look like this
<pre lang="c#">public void DoSomething(int counter)
{
}</pre>
|
|
|
|
|
Hello thanks for the help.
I had forgotten to put identity on primary key patientid
but after setting an identity,by giving the property to Patientid textbox as enable=false. when i run windows form ,the patient id textbox is blank and after entering details of all text box,radiobutton etc when i click save button the data vanishes and only patient id is displayed on form in the increasing no.I had not yet put any validation now.
also want to know ho do i reset the identity,is like "dbcc identity"
also only patient id is taken in database and rest column are taking as "0" and some as lank as pasted in question.
modified 5-Jul-13 4:58am.
|
|
|
|
|
you are inserting a record with an already existing primary key value (patientid).
I would put a break point on the insert statement check to see what the patientid is and then manually check to see if that value exists in the database
Every day, thousands of innocent plants are killed by vegetarians.
Help end the violence EAT BACON
|
|
|
|
|
ok i will try for the same.
Thanks.
|
|
|
|
|
Hi,
I am having trouble shuffling a column out of two. This is my original table below in Ms Access.
ID_EMPLOYEE ID_STATION
ALAD DECH
FRED DECI
MIKE ORR
PAM OR
RAK ORW
RAYN PROC
I would like to shuffle ID_STATION and have something different at every run. For example:
ID_EMPLOYEE ID_STATION
ALAD ORW
FRED PROC
MIKE DECI
PAM DECH
RAK OR
RAYN ORR
I am using visual studio 2012 with c#.
I created a List called scheduleList in my class SCHEDULE which contains properties like sEmployeeID and sStationID . I fill the list as follow:
List<SCHEDULE> scheduleList = new List<SCHEDULE>();
foreach (DataRow row2 in tschedule.Rows)
{
sEmployeeID = row2["ID_EMPLOYEE"].ToString();
sStationID = row2["ID_STATION"].ToString();
scheduleList.Add(new SCHEDULE(sEmployeeID, sStationID));
}
All I want now is a code to shuffle my ID_STATION only.
modified 4-Jul-13 16:26pm.
|
|
|
|
|
Create a table that holds "all possible values" or "testset" that can go into the ID_STATION, use RANDOM to fetch the values for your insert.
Bastard Programmer from Hell
If you can't read my code, try converting it here[^]
|
|
|
|
|
You could do this as below:
1. Create a new List to store all values of ID_STATION
2. Use Random class to generate a random index from 0 to upper bound value of the above List
3. Add the value corresponding to this index into a new List
4. Remove the value from the old List
5. Repeat from 2 until the old List become empty.
6. Update every record in your table
Update tableName set ID_STATION = stationList[i] where ID_EMPLOYEE = employeeList[i]
"Never memorize something that you can look up." - Albert_Einstein
|
|
|
|
|
I'm working on a string and I want to split my string in multiple strings.
e.g.- my string is String str = "Data + Value + object + system";
I want new strings like String str1 = "Data";
str2 = "Value";
str3 ="object";
str4 = "system";
How can I do this?
|
|
|
|
|
Try the String.Split method[^]:
String str = "Data + Value + object + system";
String[] parts = str.Split(new[]{ " + " }, StringSplitOptions.None);
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|