I have a C# application. Here is a piece of my code:
private const string SqlLatestFiles = "SELECT Name, [FileId],[Filename],Age,[ModifiedDT],RcvDT,[Records],[InvalidRecords],[V2Stage],[V1Stage],[FileType] FROM MyDB.[dbo].[LatestFiles] order by [ModifiedDT] DESC;";
...
using (var da = new SqlDataAdapter(SqlLatestFiles, myConnectionString))
using (var dt = new DataTable())
{
da.Fill(dt);
...
}
When I run the SqlLatestFiles in the SQL Server Management Studio, the selected data is correct. But when the DataTable dt is populated, V1Stage is 0. It didn't happen before this morning, and I doubt I could change anything. Does anybody have any idea why such thing could happen?
Thanks.
I recalled one thing that I changed yesterday: I created a copy of a database that is used in the LatestFiles view among other databases. It is the very database where the V1Stage should come from.
And yes! I removed the copy of the database, and now it works!
I guess the DataAdapter somehow confuses the two databases that yesterday were exact copies of each other.
Related
So I am having a very weird issue, At first my code to insert items into my access database stopped working, it is a simple code like this:
using (OleDbConnection myCon = new OleDbConnection())
{
OleDbCommand cmd = new OleDbCommand()
{
CommandType = CommandType.Text,
CommandText = "insert into applicationSalts ([appName],[salt]) values (?,?)"
};
cmd.Parameters.AddWithValue("#appName", appName);
cmd.Parameters.AddWithValue("#salt", salt);
myCon.ConnectionString = publicDbConnectionString;
cmd.Connection = myCon;
myCon.Open();
int result = cmd.ExecuteNonQuery();
myCon.Close();
}
So it is very straight forward, inserting those values and I checked that result = 1 (query finished successfully).
Now it gets a bit weird, The database happens to not show any new values. Which is weird, Then I tried renaming the database and then all those records appear later! I tried using the database from another location (I was using it from C:/databaseName then now used it from D:/databaseName) then it worked. I moved the database file that worked back into C, then suddenly the records that appeared before disappeared.
Much weirder is that at the beginning one of the tables in the same database used to be working with an ideantical call as the one prior to this. But this one didnt! Then when I was trying to find the issue that one also stopped working..
Also after I manually changed some records when it was working through ms access it later ignored the changes..
I am slowly going insane as I am not really understanding what is going on, This is using access 2000 file format.
Edit: After further experimentation it is still getting weirder for me, While the file is called onlineDb.mdb it had a single record, deleting that made it disappear, Now renaming it to onDb.mdb made that record come back, adding other records that were missing. Then renaming to onlineDB.mdb again made all records disappear.
Within Visual Studio 2017 I just created a DataGridView and linked a DataSource to it. It asked me for a connection string (which I gave). It showed the table from the database that I wanted in the DataGridView and it created automatically the correct columns within the DataGridView for me.
But for some reason when I start the application it does not show any data. I assume it connects to the database correctly otherwise it couldn't possibly know the name of my table and the columns within it. So how comes it sees my table but does not get the data?
So to test this I tried to make a simple RadDropDownList with help of the guide "LINK" But by following the steps for "Data binding at design time" I get the same exact result. It seems like it connects correctly but then it shows no data.
Does anyone knows why Visual Studio connects to my database with help of a DataSource but then does not gets any data from the table? Am I perhaps missing something?
Added:
I am using Microsoft SQL Server.
Yes, I have checked if the table contains data.
Try this:
string connectionString = "Data Source=.;Initial Catalog=pubs;Integrated Security=True"; // put your connection string
string sql = "SELECT * FROM Authors"; // change your table name
SqlConnection connection = new SqlConnection(connectionString);
SqlDataAdapter dataadapter = new SqlDataAdapter(sql, connection);
DataSet ds = new DataSet();
connection.Open();
dataadapter.Fill(ds, "Authors_table");
connection.Close();
dataGridView1.DataSource = ds; // put your gridview name
dataGridView1.DataMember = "Authors_table";
I'm developing a C# application and I want to copy a whole table from a SQL Server CE database to another programmatically. I know I can use this command in SQL Server, but I'm not sure how to use two database connections in one query in C#.
Select * into DestinationDB.dbo.tableName from SourceDB.dbo.SourceTable
Thanks in advance.
You wouldn't do it the same way as in SQL Server because there's no single server that manages both databases. Your app is the only thing that links the two databases so the the data has to go through your app. You're trying to do it the wrong way and that's why you can't find a solution: you're looking for the wrong thing.
There are examples of this out there. I know, because I've written more than one myself. You simply need to use a data adapter to populate a DataTable from the first database and then a data adapter to save the contents of that DataTable to the second database. If the data sources are the same type then you can even use just one data adapter because the SelectCommand and InsertCommand can have different connections.
using (var adapter = new SqlDataAdapter("SELECT statement here", "source connection string here"))
using (var destinationConnection = new SqlConnection("destination connection string here"))
using (var insertCommand = new SqlCommand("INSERT statement here", destinationConnection))
{
// Add parameters to insertCommand here.
adapter.InsertCommand = insertCommand;
// Leave the RowState of all DataRows as Added so they are ready to be inserted.
adapter.AcceptChangesDuringFill = false;
var table = new DataTable();
// Retrieve data from source and save to destination.
adapter.Fill(table);
adapter.Update(table);
}
That example uses SqlClient but it works the same for any provider, including SqlServerCe.
I am working in visual studio 2010 creating a ASP web application. I am trying to implement a search function with a grid view, where I will be passing in an ADO select command into a dataset and filling up the datagrid with my desired SQL. I know this is possible for winforms and datagridviews but for some reason, it is acting strangely on my ASP application. Here is some code...
protected void btn_search_Click(object sender, EventArgs e)
{
SqlConnection cs = new SqlConnection("Data Source=WILSON-PC; Initial Catalog=KamManOnline; Integrated Security=TRUE");
SqlDataAdapter da = new SqlDataAdapter();
DataSet ds = new DataSet();
da.SelectCommand = new SqlCommand("SELECT * FROM vw_orderView WHERE Supplier = #Supplier", cs);
da.SelectCommand.Parameters.Add("#Supplier", SqlDbType.VarChar).Value = ddl_SupplierView.Text.ToString();
ds.Clear();
da.Fill(ds);
gv_search.DataSource = ds.Tables[0];
gv_search.DataBind();
}
What happens is it picks out the right amount of data but does not show it on the grid view. For example, say if I had 3 fields as Wilson for the supplier. When I click my search button, it would bring out 3 rows but they are empty. Any ideas or another way to walk around this? Thanks!
P.S. I tried using the databind wizard but eventrually I want more flexability in my search, for example
SELECT * FROM vw_orderView WHERE (Supplier = #Supplier OR #Supplier IS NULL).
I tried writing this in the query builder but I need to add some if condition to say whether supplier will have a value or be null (check box). If this is the right approach, then please say so. Thanks
I would do the following to troubleshoot.
Run the query directly from SSMS to verify that you get back the results you expect.
Make sure the GridView has AutoGenerateColumns=true if you are not manually defining Columns.
Run in debug mode with a breakpoint set on ds.Clear() and inspect the freshly added Parameter to see that it contains the value you expect.
I am using....
Framework 3.5 C# Visual Studio 2008 and web based application
I have created reports using Dataset i.e. my service gives me data set and I bind that dataset with report.
But sometimes CR viewer started popping up error "Logon Failed" with login box with dataset name filled in login information.
I am searching for its solution for quite some time but did not fine any suitable answer to this.
This error is unfortunately ambiguous because it is the generated error for dozens of unrelated problems. In this case, the "Logon failed" is likely due to an occasional schema mismatch.
The DataSet object can contain hierarchical data. If your service is returning a DataSet containing hierarchical data, and some of the children are missing, then its schema has effectively changed.
There are several ways to ensure that the DataSet has a matching schema. If you are serializing objects into XML and then generating the DataSet from that XML, then a simple way to achieve a consistent schema is to change your code from:
reportData.ReadXml(new MemoryStream(Encoding.UTF8.GetBytes(reportXml)));
to
reportData.ReadXmlSchema(schemaPath);
reportData.ReadXml(
new MemoryStream(Encoding.UTF8.GetBytes(reportXml)),
XmlReadMode.IgnoreSchema
);
where schemaPath points to an XSD file that was generated earlier in development with a call to
File.WriteAllText(
#"C:\MyTempPath\MyReportName.xsd",
reportData.GetXmlSchema(),
Encoding.Unicode
);
When generating the schema, you will also want that schema to be as complete of a representation of the data as possible, so you will want to use as complete of a hierarchy of data as possible. This is also the XML that the report must be created off of so that its schema matches. If the schema changes, then the report must be opened in the designer with the new data and you must "verify database" and then save the RPT file.
Are you passing along your creditials in your code:
ReportDocument rep = new ReportDocument();
rep.FileName = Server.MapPath("CrystalReport1.rpt");
set.SetDatabaseLogon("username", "password", "sql-server", "database"); // this line pass the login parameters required for login
After long efforts i figured the main reason, there was a mistake in my stored procedure which was returning data.
SP returns data from table1 or table2 (they both have same structure), but when I was picking data from table2 i did not write all the column names which were required.
Seems quite weird , i should get something like column not found error instead of database logon failed.
Try this out. Also make sure you have right version of crystal report in all places
private ConnectionInfo crConnectionInfo = new ConnectionInfo();
ReportDocument rpt = new ReportDocument();
protected void Page_Load(object sender, EventArgs e)
{
CrystalReportViewer1.Width = 900;
CrystalReportViewer1.ToolPanelView = ToolPanelViewType.None;
BindReport();
}
private void BindReport()
{
rpt.Load(Server.MapPath("ProductList.rpt"));
DataSet ds = getReportData();
rpt.SetDataSource(ds.Tables[0]);
CrystalReportViewer1.ReportSource = rpt;
}
private DataSet getReportData()
{
DataSet ds = new DataSet();
string ConnectionString = ConfigurationManager.ConnectionStrings["myconn"].ConnectionString;
SqlConnection con = new SqlConnection(ConnectionString);
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "GetProductList";
cmd.CommandType = CommandType.StoredProcedure;
con.Open();
cmd.Connection = con;
SqlDataAdapter sda = new SqlDataAdapter(cmd);
sda.Fill(ds, "ctable");
con.Close();
return ds;
}
I was facing the same issue at the time, when I moved the application from the development machine to the real server. It was an IIS7 MVC application( CR 13.0) with trusted authentication to the SQL server.
The way I fixed it, was by creating a new application pool for the application. I give permission for the new application pool user IIS APPPOOL\applicationpoolname to the SQL server database that was used in the application.
Then the error went away.
My assumption is that, the userlogininfo applied through code is not always used by the CR runtime , instead it uses the IIS user login info.