Can anyone plz explain which special permission require for doing Microsoft.SqlServer.Management.Smo.Server connection via server and client both end.
i have following scenario.
server PC With Sql Server 2012 database
client PC With Only Program Which will connect database of server
i successfully got the db connection via visual stdio sqlconnectin class of remote database
but when i use Microsoft.SqlServer.Management.Smo.Server it will thrwo error for permission
can anyone help?
var connectionString = ConfigurationManager.ConnectionStrings["AppConString"].ConnectionString;
SqlConnectionStringBuilder sqlconstrbldr = new SqlConnectionStringBuilder(connectionString.ToString());
ServerConnection connection = new ServerConnection();
Microsoft.SqlServer.Management.Smo.Server sqlServer = new Microsoft.SqlServer.Management.Smo.Server(sqlconstrbldr.DataSource);
ServerName = sqlconstrbldr.DataSource;
foreach (Microsoft.SqlServer.Management.Smo.Database dbServer in sqlServer.Databases)
{
if (dbServer.Name.StartsWith("AMCS"))
{
string year = dbServer.Name;
year = year.Substring(4);
string Fyear = year.Substring(0, 2);
string Lyear = year.Substring(2);
Fyear = "20" + Fyear;
Lyear = "20" + Lyear;
string dbYear = Fyear + " - " + Lyear;
cmbDbYear.Items.Add(dbYear);
}
}
Explaination
cmbDbYear is Just Combobox in which all database names will be bonded.
MY Question is That What Remission Needed for SQL Server Management Object (Microsoft.SqlServer.Smo) must required for SQL Server Database user to successfully perform operation
i can Do Normal Database Operation currently but want also SQL Server Management Object (Microsoft.SqlServer.Smo) on database.
Related
I have a problem to connect my C# application in Visual Studio 2019 to Database inside Snyology NAS using MariaDB 10. If I connected the Database with HeidiSQL works good, but if I try to connect C# App with the same credentials I see an error like this:
"Unable to connect to any of the specified MySQL hosts"
I tried to check and I verified that:
TCP functionality is enable on Synology NAS
User and password are correct and I have all the privileges
Database name is correct
Port is also correct 3307 (setting default on Synology)
This is the code that I use to check the connection:
string connectionString = "";
string server = "ip_address_NAS:3307";
string database = "my_Database";
string username = "my_user";
string password = "my_password";
MySql.Data.MySqlClient.MySqlConnection cn;
connectionString = "SERVER=" + server + ";DATABASE=" + database + ";UID=" + username + ";PASSWORD=" + password;
try
{
cn = new MySql.Data.MySqlClient.MySqlConnection(connectionString);
cn.Open();
label1.Text = "Database ONLINE!";
label1.ForeColor = System.Drawing.Color.Green;
cn.Close();
}
catch(Exception ex)
{
label1.Text = "Database OFFLINE!\n" + ex.Message;
label1.ForeColor = System.Drawing.Color.Red;
}
Why this error?
Can you help me? please.
Thank you.
Remove the port number from the hostname. If you are connecting to the default port, there's no need to specify a port. If you are connecting to a custom port, it has to be defined in the following way
Server=myServerAddress;Port=1234;Database=myDataBase;Uid=myUsername;Pwd=myPassword
Docs
Edit
3307 is not the default port for MySQL or MariaDB. So if your database is running on port 3307 (because for whatever reason Synology has chosen it to be the initial setting) you need to specify that port in the connection string. But not as part of the servername but with the Port=3307 property.
Want to restore a database backup from linked server A to a database located on linked-server B using C#. prefer to use SMO.
I can restore from my local backup to local machine.
{
conn = new ServerConnection
{
ConnectionString = #"Data Source =
(localdb)\MSSQLLocalDb;Initial Catalog=master;Integrated Security=true",
};
try
{
//Restore Full
srv = new Server(conn);
//lsrv = srv.LinkedServers[#"DEVSQL\ALPHA"]; need to figure out how to restore to linked server instead of local.
//srv.KillAllProcesses("G4TestNew");
var res = new Restore();
res.Database = "G4TestNew";
res.Action = RestoreActionType.Database;
filePath = #"\\CABCSERVER\Database\Temp\Full.bak";
res.Devices.AddDevice(filePath, DeviceType.File);
res.ReplaceDatabase = true;
res.NoRecovery = true;
var dataFile = new RelocateFile("G4Test", #"C:\TBD\G4Test.mdf");
var logFile = new RelocateFile("G4Test_log", #"C:\TBD\G4TestNew.ldf");
res.RelocateFiles.Add(dataFile);
res.RelocateFiles.Add(logFile);
res.SqlRestore(srv);
}
EDIT(Adding more detail):.
In this case the linked servers are accessed via 'sql server authentication' and application does not have access to the credential required to connect directly and can use 'Integrated Security' to connect to localdb only.
In SMO you would not connect to one server and then administer a linked server. Instead connect directly to the target server. eg:
ConnectionString = #"Data Source =
DEVSQL\ALPHA;Initial Catalog=master;Integrated Security=true",
srv = new Server(conn);
I have a problem with my local database made with SQL Server (Local DB).
I can connect to the database on my computer but if I try to another computer, I get this error message:
I want a local database to store data, I don't need a server to manage the database.
This is my connection string:
`<connectionStrings>
<add name="stocksDB" connectionString="Data Source= (LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\myDB.mdf;Integrated Security=True;" providerName="System.Data.SqlClient"/>
</connectionStrings>`
I have included the "SQL Server 2012 Express LocalDB" in prerequisites.
What did I do wrong?
If you have two computers (lets say their machine names are "pc_a" and "pc_b" that are networked together and the program is running on computer "pc_a" and the database resides on computer "pc_b", then your connect string needs to include the machine name for computer "pc_b".
You can provide the machine name even if it is the local machine, so the code below will work if the program is running on the same machine as the database or if the program is running on one machine and the database is on another, so long as the two machines are networked AND the account you're running the program under has access to the machine and instance and database.
Please note in example below, the "default" instance name (MSSQLSERVER) was used when SQL was installed. When the DB instance name is the default name, then you must not provide an instance name explicitly (you'll get the error you showed if you do). The only time you provide an instance name explicitly is when it it not the default instance name. The code below can handle either scenario (by setting dbInstanceName variable to "" or an instance name, e.g. "\SQLEXPRESS"). See S.O. SQL Server: How to find all localdb instance names. When it doubt, try an empty instance name and a name you believe to be the instance name to see what works.
string databaseMachineName = "pc_b";
string databaseInstanceName = "";
string dbName = "stocksDb";
using (SqlConnection sqlConnection = new SqlConnection("Data Source=" + databaseMachineName + databaseInstanceName + "; Initial Catalog=" + dbName + "; Integrated Security=True;Connection Timeout=10"))
{
.
.
.
}
Solved! The problem was the wrong SQL Server version on the other computer. On my main computer I have SQL Server 2014 and on the other one the 2012 version so the "database instance name" was different. Thanks to #Nova Sys Eng for the input!
Now I changed my connection string:
First of all I used a code to retrieve all the SQL server instances installed on the computer as explained on the link posted by Nova Sys Eng.
var instances = GetLocalDBInstances();
var connString= string.Format("Data Source= (LocalDB)\\{0};AttachDbFilename=|DataDirectory|\\myDB.mdf;Integrated Security=True;",instances[0]);
internal static List<string> GetLocalDBInstances()
{
// Start the child process.
Process p = new Process();
// Redirect the output stream of the child process.
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.FileName = "cmd.exe";
p.StartInfo.Arguments = "/C sqllocaldb info";
p.StartInfo.CreateNoWindow = true;
p.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
p.Start();
// Do not wait for the child process to exit before
// reading to the end of its redirected stream.
// p.WaitForExit();
// Read the output stream first and then wait.
string sOutput = p.StandardOutput.ReadToEnd();
p.WaitForExit();
//If LocalDb is not installed then it will return that 'sqllocaldb' is not recognized as an internal or external command operable program or batch file.
if (sOutput == null || sOutput.Trim().Length == 0 || sOutput.Contains("not recognized"))
return null;
string[] instances = sOutput.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
List<string> lstInstances = new List<string>();
foreach (var item in instances)
{
if (item.Trim().Length > 0)
lstInstances.Add(item);
}
return lstInstances;
}
I am trying to retrieve data from a database with the following code:
public partial class populate : System.Web.UI.Page
{
SqlConnection scon = new SqlConnection("Data Source = localhost; Integrated Security = true; Initial Catalog = populate");
protected void Page_Load(object sender, EventArgs e) {
StringBuilder htmlString = new StringBuilder();
if(!IsPostBack)
{
using (SqlCommand scmd = new SqlCommand())
{
scmd.Connection = scon;
scmd.CommandType = CommandType.Text;
scmd.CommandText = "SELECT * FROM populate";
scon.Open();
SqlDataReader articleReader = scmd.ExecuteReader();
htmlString.Append("'Populate page:'");
if (articleReader.HasRows)
{
while (articleReader.Read())
{
htmlString.Append(articleReader["dateTime"]);
htmlString.Append(articleReader["firstName"]);
htmlString.Append(articleReader["lastName"]);
htmlString.Append(articleReader["address"]);
htmlString.Append(articleReader["details"]);
}
populatePlaceHolder.Controls.Add(new Literal { Text = htmlString.ToString() });
articleReader.Close();
articleReader.Dispose();
}
}
}
}
}
It's throwing an error:
The system cannot find the file specified
I am wondering if someone can show me where the error is or guide me through debugging this. Thanks in advance.
(update): More specifically, the scon.Open() is causing the error:
Message=A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)
This looks easy enough to fix, but I'm not very good with the database. Any help will be appreciated.
I don't know what SQL Server edition you have installed, and what you called it (as an instance name) .....
Go to Start > SQL Server > Configuration Tools > Configuration Manager; under SQL Server Services, search for the SQL Server service - what is it's name??
If it's SQL Server (SQLEXPRESS), then that means you have the Express edition, with an instance name of SQLEXPRESS - change your connection string to:
Data Source=.\SQLEXPRESS;Initial Catalog=populate;Integrated Security=true;
If it's SQL Server (MSSQLSERVER) then you should be fine really - you have an unnamed, default instance ....
I have this code in Transaction.cs
using (TransactionScope scope = new TransactionScope())
{
// Setup nhibernate configuration
Configuration config = new Configuration();
config.SetProperty("hibernate.connection.connection_string", GlobalVar.TRUECONNSTRING);
config.SetProperty("hibernate.command_timeout", "3600");
config.AddAssembly(typeof(ProductionMovein).Assembly);
// Setup nhibernate session
ISessionFactory factory = config.BuildSessionFactory();
ISession session = factory.OpenSession();
ITransaction transaction = session.BeginTransaction();
//Recalculate Number
PairData pairCabang = (PairData)comboCabang.SelectedItem;
textNo.Text = FormFunction.getNumber(2, pairCabang.key, dtpTanggal.Value);
// Insert data
try
{
//ProductionMoveIn
ProductionMovein productionMoveIn = new ProductionMovein();
productionMoveIn.Nomor = textNo.Text;
session.Save(productionMoveIn);
transaction.Commit();
session.Close();
}
catch (Exception ex)
{
transaction.Rollback();
session.Close();
MessageBox.Show(ex.InnerException.Message);
return 1;
}
scope.Complete();
}
And the error is started from
textNo.Text = FormFunction.getNumber(2, pairCabang.key,
dtpTanggal.Value);
i have this code in Formfunction.cs
public static string getNumber(int formID, int cabangID, DateTime date)
{
string formNumber = "";
string strQuery = "";
formNumber += formNames[formID, 0] + "/" + + date.ToString("yy") + date.ToString("MM") + "/";
// Setup nhibernate configuration
NHibernate.Cfg.Configuration config = new NHibernate.Cfg.Configuration();
config.SetProperty("hibernate.connection.connection_string", GlobalVar.TRUECONNSTRING);
config.SetProperty("hibernate.command_timeout", "3600");
config.AddAssembly(typeof(Login).Assembly);
//// Setup nhibernate session
ISessionFactory factory = config.BuildSessionFactory();
ISession session = factory.OpenSession();
strQuery = "SELECT MAX(REVERSE(SUBSTRING(REVERSE(a.Nomor), 1, 5))) as 'latest' FROM " + formNames[formID, 1] +
" a WHERE a.cabang = " + cabangID +
" AND YEAR(a.tanggal) = '" + date.ToString("yyyy");
Object result = session.CreateSQLQuery(strQuery)
.AddScalar("latest", NHibernateUtil.Int32)
.UniqueResult();
session.Close();
int nRow;
if (result == null)
nRow = 0;
else
nRow = (int)result;
formNumber += (nRow + 1).ToString("d5");
return formNumber;
}
I have tried to change the Server to 10.10.7.10 (my ip) and it works. but, when i change to other ip, it cannot open connection.
I have tried to turn on msdtc on my computer and the other server i tried to connect, but still get the same error.
Can anybody help me how to solve this error?
Which database are you using? (I've assumed MS SQL)
Can you post the exception detail please?
Here's an approach.
First comment out the using (TransactionScope) / scope.Complete
and try connect to the remote database - i.e. to ensure that your
local Sql client is configured for TCP/IP, the remote server allows
remote TCP/IP connections (usually port 1433), and that your login
credentials and access are correct.
DTC is usually only required when 2 or more connections are used. If
you reinstate the TransactionScope, but then remove the NHibernate
transaction, then DTC might not be required at all. Also note that
TransactionScopes default to Read Serializable isolation -
TransactionScope functions
Ensure that DTC is configured on both your PC and the Server to
allow remote connections etc - .
You also need to tackle firewall issues
DTC firewall requirements?
EDIT
By default, SQL Express isn't open to remote connections - on the remote server, you will need to enable TCP/IP on SQL Configuration Manager, open up the firewall for 1433 / 1434, and as #Özgür mentions, ensure that the SQL the browser service is running (or change your instance name, or change your connection string to use ip, port). More on this here : http://www.sevenforums.com/system-security/58817-remote-access-sql-server-express-2008-windows-7-a.html