Gridview Population - c#

I have been looking at this code all weekend. I know there is data and I can pull it through other queries but the GridView will not show and populate. Suggestions?
string sqlSelection =
"SELECT * FROM [COMPANY].[dbo].[parking] ";
SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["DATACONNECTION"].ToString());
//This connection works in MSSMS and in other pages I have on the same server
SqlDataAdapter sda = new SqlDataAdapter(sqlSelection, cn);
SqlCommandBuilder scb = new SqlCommandBuilder(sda);
DataTable dTable = new DataTable();
sda.Fill(dTable);
//debug shows: dTable <not set>
GrdDynamic.Visible = true;
GrdDynamic.DataSource = dTable;
GrdDynamic.DataBind();

I have had this behavior when the account in the connection string doesn't have rights to the database because the account the web service doesn't have access to the account. If you are using a machine account (not a sql login) try to create a sql login (if possible) and assign it to the db. Or you can temporarily using the anonymous account to use the login you are using for the management studio (more than likely yourself). I have also had this happen when the web server could not see the SQL server due to routing issues. You can test the last one by going to the server and trying to ping the sql server. The worst one situation is when a firewall has stopped the port from connecting. I am not sure of a sure fire test for this situation because it depends a lot of how your network is configured.

Related

Can't access my SQL Server without SQL Engine

I have two computers. One is running SQL Server, and I can access the server using SQL authentication from the 2nd PC using SSMS.
I have created a C# Windows Forms application that connects to the database. However, I couldn't access my server from the application.
I disabled the firewall, allowed remote control, and allowed mixed mode authentication. I also forwarded required ports to my IP in my router settings.
I tried both these connecting strings, but they didn't help:
"Persist Security Info = False; User ID = gues; Password=gues;Initial Catalog = CoronaNurse; Server=" + server;
"Data Source=" + server + ";Initial Catalog=CoronaNurse;Integrated Security=false;UID=gues;Password=gues";
(server is a string that have IP of my server)
(gues is a login in my Server)
The weird thing is when I login as gues in SSMS from my 2nd computer I can access the server in the first computer.
The question is, how do I access my server from a computer that doesn't have SSMS or any specific Login?
I need my application to be able to connect to my server without anything else installed, but I can't find where my problem is.
Adding from comments:
Im using the connecting to get a con string from my DB depends on the table i get with my gue.login function SqlDataAdapter
adapter = new SqlDataAdapter("select * from gue.login('" + textBox1.Text.Trim() + "', '" + textBox2.Text.Trim() + "', '" + server + "')", conn);
SqlCommandBuilder cb = new SqlCommandBuilder(adapter);
DataSet ds = new DataSet();
adapter.Fill(ds);
string connection;
connection = ds.Tables[0].Rows[0][0].ToString();
Unless you haven't posted up all of your code, you don't appear to be controlling your SQL connection and I would strongly suggest that you use a parameterised call to protect against SQL injection from using direct text entry field values e.g.:
var dataset = new DataSet();
using (var connection = new SqlConnection(SqlConnectionString))
{
connection.Open();
var command = new SqlCommand("GetAll", connection);
command.CommandType = CommandType.StoredProcedure;
var adapter = new SqlDataAdapter(command);
adapter.Fill(dataset);
...
}
The SQL is wrong, and the connection strings look a little off. You might also need an instance name as part of the server. For example, instead of just localhost or 192.168.0.20, you might need localhost\SQLExpress or 192.168.0.20\..
One way you can find the connection string for sure is to use Visual Studio instead of SSMS to connect to the database. The Visual Studio Database Tools has a similar connection window as SSMS, and you can use it to show you the actual connection string it used.
When you've figured that out, try something more like this:
var connString = $"Server={server};Database=CoronaNurse;User Id=gues;Password=gues";
var sql = "select * from gue.login WHERE username = #username AND pHash = #pHash";
var ds = new DataSet();
using (var conn = new SqlConnection(connString))
using (var cmd = new SqlCommand(sql, conn))
using (var adapter = new SqlDataAdapter(cmd))
{
cmd.Parameters.Add("#username", SqlDbType.NVarChar, 50).Value = textBox1.Text.Trim();
cmd.Parameters.Add("#pHash", SqlDbType.Char, 60).Value = BCrypt.Net.BCrypt.HashPassword(textBox2.Text.Trim());
adapter.Fill(ds);
var connection = ds.Tables[0].Rows[0].Items[0].ToString();
}
Note the use of both parameterized queries and BCrypt (you can add BCrypt via NuGet). There are a few things in database development that are too important to do wrong, even for proof-of-concept and learning projects. One of these is SQL Injection. Another is password handling. What I posted still isn't quite right for password handling (you should instead retrieve the stored hash and use the Verify() method), but it's close enough to set you on the right path.
Someone has told me that I can't access my online SQL Server DB from a client PC that doesn't have a Local DB.
I guess that explains my problem perfectly!
I never knew that, in my case, that is my problem right?

How to connect to phpmyadmin mysql database using c# (using Mysql.Data.MysqlClient;)

I am trying to connect to the MySQL database using this code client_v is the name of the table I want to get data from.
I went through a lot of similar questions here but I really haven't found an answer to this question.
using MySql.Data.MySqlClient;
private void Form1_Load(object sender, EventArgs e) {
try {
string connetionstring = "Server=a029um.forpsi.com;Uid=userlogin;Pwd=userpassword";
string mysql = "SELECT * FROM dbname.cilent_v";
MySqlConnection conn = new MySqlConnection(connetionstring);
MySqlCommand command = new MySqlCommand(mysql, conn);
conn.Open();
MySqlDataAdapter dtb = new MySqlDataAdapter();
dtb.SelectCommand = command;
DataTable dtable = new DataTable();
dtb.Fill(dtable);
dataGridView1.DataSource = dtb;
} catch(Exception ex) {
MessageBox.Show(ex.Message);
}
}
The error it is returning:
Unable to connect to any of the specified MySQL hosts.
Initially, I can see that you miss the Database part in your connection string.
Be sure that your connection string is valid (including valid user name and password)
For MySql, you can find here all example list
https://www.connectionstrings.com/mysql/
I also noticed that your server is hosted on the cloud (most likely shared hosting) so you need to contact the service provider and ask them to add your computer's public IP to their firewall to accept your connection.
The better practice, for the development environment, install the MySql engine and WorkBench on your local PC, and finally when you reach the point to deploy, that time change the connection string to connect to the cloud-hosted Database.
To install MySql Engine see
https://dev.mysql.com/doc/mysql-installation-excerpt/5.7/en
To install WorkBench (The database management studio) see https://dev.mysql.com/doc/workbench/en/wb-installing-windows.html
How to use WorkBench, just google some training videos on the internet.

Select record from multiple database

I'm using Microsoft SQL Server 2008 R2 and asp.net for C#.
Currently I'm doing an intranet. It consists of many modules inside intranet. Each module uses its own database. Normally I will using connection string for calling to the database.
I plan to do a main page to manage all pending tasks inside each module. Means on the main page, I will show all the pending tasks of all modules. Since they are all using different connection strings, what approaches can be used to achieve this?
The example below show how I access database through single connection string:
string connectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
string strsql = " select * from User ";
SqlConnection con = new SqlConnection(connectionString);
SqlDataAdapter da = new SqlDataAdapter(strsql, connectionString);
con.Open();
DataSet ds = new DataSet();
da.Fill(ds);
con.Close();
con.Dispose();
Create a proc where you can call table of different database with respective Db names.
create proc proc_name
as begin
select * from [DB_name1].dbo.tablename
union all
select * from [DB_name2].dbo.tablename
end
now call the proc from your code behind.
No matter what ever db name in your connection string,still you can access
Note: check your DB has rights to access other DB.

Copy a whole table from a SQL Server CE database to another

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.

C# windows service is still running but non-responsive

I have c# window service created in server. Which has sqlite database. Client machine uses c# windows form application to connect to server and get data from server db.
So as first thing client application login to server using http request. And server receives the request and send back the data to client.
But sometimes even if the service is running the server is not responsive to the client and client is not able to connect to server. Later i restart the service and then it connects.
System.Data.DataSet rdr = db.ExecuteDataSet(#"
select i.id
from item i,field f
where i.typeid=1 and
f.value like '" + UserName + "' and i.id=f.itemid");
if (rdr.Tables[0].Rows.Count == 0)
{
rdr = null;
return false;
}
public DataSet ExecuteDataSet(String sqlExpr)
{
if (conn.State != ConnectionState.Open)
Open(DataFile);
SQLiteDataAdapter _adapter = new SQLiteDataAdapter(sqlExpr, conn);
DataSet ds = new DataSet();
_adapter.Fill(ds);
return ds;
}
Above is the code for login .Is there something blocking db. Please help me with your valuable answers.
Regards
Sangeetha
I dont have sure, but, if the loggin works well, the problem seems like have a error in the server, when you open the connection with de sqlite you close it after use?
the sqlite have some routine to kill connection in sleep?
Other thing, did you use the component.dispose()? because if you dont dispose the components, they keep use memory.

Categories