Using .NET's DbConnection.GetSchema(), how do I find the owner of a given database?
Alternatively, if you have another solution that is not coupled to a specific impelementation of SQL, I'd like to hear that as well.
The GetSchema call of DbConnection unfortunately doesn't retrieve the DB owner for you :-(
But you can try this on SQL Server:
select
db.name, db.database_id, l.name, l.type
from
sys.databases db
inner join
sys.login_token l on db.owner_sid = l.sid
If you want to connect to SQL Server from .NET, you could use the SMO (SQL Management Objects) and find your owner like this:
Server server = new Server("Your Server");
Database db = server.Databases["Your Database"];
Console.WriteLine("Database owner is: " + db.Owner);
Marc
I don't believe that the SQL-92 standard specifies that a Catalog (a database) must have an owner. As such, I don't know that you can get a non-implementation-specific way of doing this.
Related
I'm using Signalr with SqlDependency. My code works and it shows me realtime results like I wanted. But the issue is it is working my newly created database. If I change the database to old one the SqlDependency stops work and not getting the change detection on my database table.
Below is my code:
#region SignalRMethods
[System.Web.Script.Services.ScriptMethod()]
[System.Web.Services.WebMethod(EnableSession = true)]
public GlobalApplicationError[] GetErrorsList()
{
var cs = "Data Source=.;Initial Catalog=NotifyDB;Integrated Security=True";
using (var connection = new SqlConnection(cs))
{
connection.Open();
SqlDependency.Start(cs);
using (SqlCommand command = new SqlCommand(#"SELECT [Form_Name],[Message],[Prepared_By_Date] FROM [GlobalApplicationError]", connection))
{
// Make sure the command object does not already have
// a notification object associated with it.
SqlDependency dependency = new SqlDependency(command);
dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);
if (connection.State == ConnectionState.Closed)
connection.Open();
using (var reader = command.ExecuteReader())
return reader.Cast<IDataRecord>()
.Select(x => new GlobalApplicationError()
{
Form_Name = x["Form_Name"].ToString(),
Message = x["Message"].ToString(),
Prepared_By_Date = Convert.ToDateTime(x["Prepared_By_Date"])
}).ToList().ToArray();
}
}
}
private static void dependency_OnChange(object sender, SqlNotificationEventArgs e)
{
MyHub.Show();
}
#endregion
Above code perfectly works on database NotifyDB but not on my existing one which is eprocure if I change the database in my connection string. As I'm using the asmx web service so I always update the reference of my web service. Plus I've enable_broker set to true on both databases.
Database screen shots:
NotifyDB
eprocure
output
Kindly let me know what I'm doing wrong in my code. Thanks in advance.
Let windup this. After some brainstorming on internet I successfully found my answer.
I've Checked my database sys.transmission_queue using below query:
select * from sys.transmission_queue
As most likely our notification(s) will be there, retained because they cannot be delivered. The transmission_status have an explanation why is this happening.
I found that there is below error:
Error: 15517, State: 1. Cannot execute as the database principal because the principal "dbo" does not exist
Google it and found the below useful link:
Troubleshooting SQL Server Error 15517
after that I run the below query which is briefly defined in above link
EXEC sp_MSForEachDB
'SELECT ''?'' AS ''DBName'', sp.name AS ''dbo_login'', o.name AS ''sysdb_login''
FROM ?.sys.database_principals dp
LEFT JOIN master.sys.server_principals sp
ON dp.sid = sp.sid
LEFT JOIN master.sys.databases d
ON DB_ID(''?'') = d.database_id
LEFT JOIN master.sys.server_principals o
ON d.owner_sid = o.sid
WHERE dp.name = ''dbo'';';
By doing this, I found several databases that sys.databases said had an owner. However, when I checked it from the database's sys.database_principals, the SID didn't match up for dbo. The column I had for dbo_login came back NULL. That was a clear sign of the issue. There is also the possibility you will see a mismatch between dbo_login and sysdb_login. It appears that as long as dbo_login matches a legitimate login, the error is not generated. I found that on some DBs on one of my servers. While it's not causing a problem now, I'll be looking to correct the mismatch.
Correcting the Error:
The easiest way to correct the error is to use ALTER AUTHORIZATION on the databases which have the NULL login match for dbo. It's as simple as:
ALTER AUTHORIZATION ON DATABASE::eprocure TO sa;
So finally. I got what I want and my SQL Dependency is working fine. This is all from my end. Thanks you help me on this post. I appreciate for your precious time. Happy Coding.
Please make sure Query Notifications & Service broker are enabled and permissions for the IIS identify are granted.
Steps to enable : https://techbrij.com/database-change-notifications-asp-net-signalr-sqldependency
To check service broker is enabled execute the below statement
SELECT name, is_broker_enabled FROM sys.databases
To enable service broker
ALTER DATABASE <<DatabaseName>> SET ENABLE_BROKER
To grant permission to a user
GRANT SUBSCRIBE QUERY NOTIFICATIONS TO “<<USERIDENTITY>”
I'm working on a pretty special, legacy project where I need to build an app for PDA devices under Windows Mobile 6.5. The devices have a local database (SQL Server CE) which we are supposed to sync with a remote database (Microsoft Access) whenever they are docked and have network access.
So the local database using SQL Server CE works fine, but I can’t figure out a way to sync it to the Access database properly.
I read that ODBC and OLEDB are unsupported under Windows Mobile 6.5, most ressources I find are obsolete or have empty links, and the only way I found was to export the local database relevant tables in XML in the hope to build a VBA component for Access to import them properly. (and figure out backwards sync).
Update on the project and new questions
First of all, thanks to everyone who provided an useful answer, and to #josef who saved me a lot of time with the auto path on this thread.
So a remote SQL Server is a no go for security reasons (client is paranoid about security and won't provide me a server). So I'm tied to SQL Server CE on the PDA and Access on the computer.
As for the sync:
The exportation is fine: I'm using multiple dataAdapters and a WriteXML method to generate XML files transmitted by FTP when the device is plugged back in. Those files are then automatically imported into the Access database. (see code at the end).
My problem is on the importation: I can acquire data through XML readers from an Access-generated file. This data is then inserted in a dataset (In fact, I can even print the data on the PDA screen) but I can't figure out a way to do an "UPSERT" on the PDA's database. So I need a creative way to update/insert the data to the tables if they already contains data with the same id.
I tried two methods, with SQL errors (from what I understood it's SQL Server CE doesn't handle stored procedures or T-SQL). Example with a simple query that is supposed to update the "available" flag of some storage spots:
try
{
SqlCeDataAdapter dataAdapter = new SqlCeDataAdapter();
DataSet xmlDataSet = new DataSet();
xmlDataSet.ReadXml(localPath +#"\import.xml");
dataGrid1.DataSource = xmlDataSet.Tables[1];
_conn.Open();
int i = 0;
for (i = 0; i <= xmlDataSet.Tables[1].Rows.Count - 1; i++)
{
spot = xmlDataSet.Tables[1].Rows[i].ItemArray[0].ToString();
is_available = Convert.ToBoolean(xmlDataSet.Tables[1].Rows[i].ItemArray[1]);
SqlCeCommand importSpotCmd = new SqlCeCommand(#"
IF EXISTS (SELECT spot FROM spots WHERE spot=#spot)
BEGIN
UPDATE spots SET available=#available
END
ELSE
BEGIN
INSERT INTO spots(spot, available)
VALUES(#spot, #available)
END", _conn);
importSpotCmd.Parameters.Add("#spot", spot);
importSpotCmd.Parameters.Add("#available", is_available);
dataAdapter.InsertCommand = importSpotCmd;
dataAdapter.InsertCommand.ExecuteNonQuery();
}
_conn.Close();
}
catch (SqlCeException sql_ex)
{
MessageBox.Show("SQL database error: " + sql_ex.Message);
}
I also tried this query, same problem SQL server ce apparently don't handle ON DUPLICATE KEY (I think it's MySQL specific).
INSERT INTO spots (spot, available)
VALUES(#spot, #available)
ON DUPLICATE KEY UPDATE spots SET available=#available
The code of the export method, fixed so it works fine but still relevant for anybody who wants to know:
private void exportBtn_Click(object sender, EventArgs e)
{
const string sqlQuery = "SELECT * FROM storage";
const string sqlQuery2 = "SELECT * FROM spots";
string autoPath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase); //get the current execution directory
using (SqlCeConnection _conn = new SqlCeConnection(_connString))
{
try
{
SqlCeDataAdapter dataAdapter1 = new SqlCeDataAdapter(sqlQuery, _conn);
SqlCeDataAdapter dataAdapter2 = new SqlCeDataAdapter(sqlQuery2, _conn);
_conn.Open();
DataSet ds = new DataSet("SQLExport");
dataAdapter1.Fill(ds, "stock");
dataAdapter2.Fill(ds, "spots");
ds.WriteXml(autoPath + #"\export.xml");
}
catch (SqlCeException sql_ex)
{
MessageBox.Show("SQL database error: " + sql_ex.Message);
}
}
}
As Access is more or less a stand-alone DB solution I strongly recommend to go with a full flavored SQL Server plus IIS to setup a Merge Replication synchronisation between the SQL CE data and the SQL Server data.
This is described with full sample code and setup in the book "Programming the .Net Compact Framework" by Paul Yao and David Durant (chapter 8, Synchronizing Mobile Data).
For a working sync, all changes to defined tables and data on the server and the CE device must be tracked (done via GUIDs, unique numbers) with there timestamps and a conflict handling has to be defined.
If the data is never changed by other means on the server, you may simply track Device side changes only and then push them to the Access database. This could be done by another app that does Buld Updates like described here.
If you do not want to go the expensive way to SQL Server, there are cheaper solutions with free SQLite (available for CE and Compact Framework too) and a commercial Sync tool for SQLite to MSAccess like DBSync.
If you are experienced, you may create your own SQLite to MS ACCESS sync tool.
I use C#, .net 4, Entity Framework and SQL Server 2008 R2 in a project.
I have no familiarity with backup and restore from database by Entity Framework. Please help me to write restore and backup code in Entity Framework
Entity Framework is an ORM - object-relational mapper - designed to handle interactions with single entities and/or short lists of entities. It's neither designed for bulk operations, nor is it a server admin framework. So no - I don't think you can do this using Entity Framework - that's not its job.
Use an appropriate tool for the job! Either use SQL Server Management Studio to handle backup/restore - or if you must do it programmatically, use the SMO (Server Management Objects) which is intended for exactly these kinds of jobs
To other friends who have this problem ....
Useing ExecuteSqlCommand can backup of db in EF 6+ .
For example : (this code create backup of your DB , I had tested this.)
string dbname = db.Database.Connection.Database;
string sqlCommand = #"BACKUP DATABASE [{0}] TO DISK = N'{1}' WITH NOFORMAT, NOINIT, NAME = N'MyAir-Full Database Backup', SKIP, NOREWIND, NOUNLOAD, STATS = 10";
db.Database.ExecuteSqlCommand(System.Data.Entity.TransactionalBehavior.DoNotEnsureTransaction, string.Format(sqlCommand,dbname, "Amin9999999999999"));
backup saved in C:\Program Files\Microsoft SQL Server\MSSQL10.SQLEXPRESS\MSSQL\Backup
ref=> https://entityframework.codeplex.com/discussions/454994
but I do not recommend for working with this method!
I strongly recommend the use of the article below:
http://www.c-sharpcorner.com/Blogs/8679/backup-and-restore-the-database-in-Asp-Net-web-application.aspx
This should get you going on the restore side:
void LoadDB(
System.Data.Entity.DbContext context,
string backup_filename,
string orig_mdf, // the original LogicalName name of the data (also called the MDF) file within the backup file
string orig_ldf, // the original LogicalName name of the log (also called the LDF) file within the backup file
string new_database_name
)
{
var database_dir = System.IO.Path.GetTempPath();
var temp_mdf = $"{database_dir}{new_database_name}.mdf";
var temp_ldf = $"{database_dir}{new_database_name}.ldf";
var query = #"RESTORE DATABASE #new_database_name FROM DISK = #backup_filename
WITH MOVE #orig_mdf TO #temp_mdf,
MOVE #orig_ldf TO #temp_ldf,
REPLACE;";
context.Database.ExecuteSqlCommand(
// Do not use a transaction for this query so we can load without getting an exception:
// "cannot perform a backup or restore operation within a transaction"
TransactionalBehavior.DoNotEnsureTransaction,
query,
new[] {
new SqlParameter("#backup_filename", backup_filename),
new SqlParameter("#database_dir", database_dir),
new SqlParameter("#new_database_name", new_database_name),
new SqlParameter("#orig_mdf", orig_mdf),
new SqlParameter("#orig_ldf", orig_ldf),
new SqlParameter("#temp_mdf", temp_mdf),
new SqlParameter("#temp_ldf", temp_ldf),
}
);
}
If you don't know them beforehand, the MDF and LDF LogicalName values can be obtained manually or programmatically from a query like this one:
RESTORE FILELISTONLY FROM DISK #backup_filename
How we select data from SDF (webmatrix) database in visual studio with Linq just like we can with northwind, like this:?
// Northwnd inherits from System.Data.Linq.DataContext.
Northwnd nw = new Northwnd(#"northwnd.mdf");
// or, if you are not using SQL Server Express
// Northwnd nw = new Northwnd("Database=Northwind;Server=server_name;Integrated Security=SSPI");
var companyNameQuery =
from cust in nw.Customers
where cust.City == "London"
select cust.CompanyName;
foreach (var customer in companyNameQuery)
{
Console.WriteLine(customer);
}
Ref: http://msdn.microsoft.com/en-us/library/bb399398.aspx
please thank you for your help.
I don't believe that Linq To SQL is officially supported with SQL Server CE 4.0, although it appears you can get it working. Microsoft's recommended approach is to use the Entity Framework.
I've written a couple of articles on using EF with SQL Server CE in WebMatrix. One covers the Code First approach, and the other looks at a database first approach.
I have developed a program (C#) which creates a SQL database using this code:
string SQLCreation = "IF NOT EXISTS (SELECT * FROM master..sysdatabases WHERE Name = 'x') CREATE DATABASE x";
SqlConnection PublicSQLDBCreationConnection = new SqlConnection(connectionString);
SqlCommand PublicSQLDBCreation = new SqlCommand(SQLCreation, PublicSQLDBCreationConnection);
try
{
PublicSQLDBCreationConnection.Open();
PublicSQLDBCreation.ExecuteNonQuery();
PublicSQLDBCreationConnection.Close();
}
//'then creates a table and so on
Now I want to have a client application which connects to this database (via LAN) WITHOUT using IP or computer name. How is that possible? Is it possible do this and have a dataset while not mentioning IP Adr. or computer name?
P.S. Don't Worry Guys, I simplified my code just for your view, I have made sure that SQL injection or other attempts won't happen.
Also I have to say that My Reason for not mentioning servername or IP is that I want to mass deploy my Application on many Networks
You could use SqlDataSourceEnumerator to get a list of all Sql Servers that are visible and browsable. This is not a good technique, since you could get an instance that you don't have the right to create a database on it, but you could still try something with that.
var enumerator = SqlDataSourceEnumerator.Instance;
foreach (DataRow row in enumerator.GetDataSources().Rows)
{
var serverName = row["ServerName"];
var instance = row["InstanceName"];
// build a connection string and try to connect to it
}