Cannot open connection if the server is not local - c#

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

Related

Connect and insert data from my computer to server's MySQL DB table with the help of C#.NET

I want to connect with a server's MySql DB(cpanel) . Though there are no errors every time I'm getting a message for Messegebox : unable to connect to any of the specified any of the MySql hosts.
using MySql.Data.MySqlClient;
connString = "SERVER = ********;PORT=3306;DATABASE=********;UID=**********;PASSWORD=*********";
try
{
conn = new MySqlConnection();
conn.ConnectionString = connString;
conn.Open();
MessageBox.Show("Server is online");
}
catch (MySql.Data.MySqlClient.MySqlException ex)
{ MessageBox.Show(ex.Message);}
If you try to connect to your MySQL server externally, external connections need to be enabled.
Be aware that it is a security hole if you provide your app to others which contain the DB information. To go around that, you need to create a Web-API.
The first step to connect to your app to a remote server MySql Server is verify if it allows external connections, for default the root user is locked, to allow local you can try to connect with the root user typing the following command in MySql:
GRANT ALL PRIVILEGES ON *.* TO 'root'#'%' IDENTIFIED BY 'password' WITH GRANT OPTION;
FLUSH PRIVILEGES;
'root': You can change it with your user.
'%': allows all connections, you can limit it typing an IP.
Second step is verify your MySql .net connector
Cheers!
I would look into using ConnectionStringBuilder. Also note the use of 'using'. This will ensure resources are disposed once finished with.
private MySqlConnectionStringBuilder sConnString = new MySqlConnectionStringBuilder
{
Server = "",
UserID = "",
Password = "",
Database = ""
};
private void Test(){
// open connection to db
using (MySqlConnection conn = new MySqlConnection(sConnString.ToString()))
{
using (MySqlCommand cmd = conn.CreateCommand())
{
try
{
conn.Open();
cmd.CommandText = "SELECT * FROM foo WHERE OrderID = #OrderID";
// Add any params
cmd.Parameters.AddWithValue("#OrderID", "1111");
cmd.Prepare();
cmd.ExecuteNonQuery();
}
catch (Exception e)
{
MessageBox.Show(e.ToString());
return;
}
}
}
}

LocalDB connections visible in SQL management studio

In my unit tests, I'm using a SQL Server LocalDB database. You could be nit picky and say that because of that fact it's not unit tests but integration tests and you would be right, but the point is that I am using the MSTest Framework to run those tests. Every test is copying an existing database and running their one test on this database.
private NAMETestSystem([CallerMemberName] string testCase = null)
{
this.destinationDirectory = Path.Combine(Directory.GetCurrentDirectory(), testCase ?? "Undefined_" + Guid.NewGuid().ToString("N"));
var connectionString = $"Data Source=(LocalDB)\\MSSQLLocalDB; Integrated Security = True; AttachDbFilename ={Path.Combine(this.destinationDirectory, "NAMEIntegrationTest.mdf")}";
var entityFrameworkData = $"metadata=res://*/NAME.csdl|res://*/NAME.ssdl|res://*/NAME.msl;provider=System.Data.SqlClient;provider connection string=\"{connectionString}\"";
// [...]
Copy(SourceDirectory, this.destinationDirectory);
My "problem" is that each of those copies pops up in my SQL Server management studio. All 100+ or them. I don't need them there. They don't exist anymore. And to make things worse, you cannot batch-detach... I have to press Del+Enter about 150 times just to clear that window up.
Is there a way to not have my temporary local db instances appear in my SQL server management studio?
Maybe special way to close or dispose, something in the connection string I can set? Or maybe a way to detach all of them at the same time in management studio?
So in the end, what I did and what is working fine for now is this:
public void Dispose()
{
// disposing other stuff
// sql db
if (Directory.Exists(this.destinationDirectory))
{
DetachDatabase(this.connectionString);
Directory.Delete(this.destinationDirectory, true);
}
}
public static void DetachDatabase(string connectionString)
{
using (var connection = new SqlConnection(connectionString))
{
connection.Open();
using (var command = connection.CreateCommand())
{
var sql = "DECLARE #dbName NVARCHAR(260) = QUOTENAME(DB_NAME());\n" +
"EXEC('ALTER DATABASE ' + #dbName + ' SET OFFLINE WITH ROLLBACK IMMEDIATE;');\n" +
"EXEC('exec sp_detach_db ' + #dbName + ';');";
command.CommandText = sql;
command.ExecuteNonQuery();
}
}
}
Might not be the prettiest solution, but at least it keeps my sanity intact while the number of tests (and number of databases) rises.

Can`t Permit Microsoft.SqlServer.Management.Smo.Server via database permission

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.

How to test connection to a data source in SSAS using C#

I have a database in Analysis Services on a remote server. This contains a data source for another database located on another remote server.
I am trying to write a connectivity test using C# which will check the database connection between the two databases.
I have been unable to do this using ADOMD.NET. I'm currently looking at using SMO to do this but I haven't had any luck so far.
I would greatly appreciate any advice or suggestions.
Update:
After further research, I have come up with the below test (Please note that I intend to add more try..catch blocks and Assertions later).
Also, this uses C:\Program Files\Microsoft SQL Server\100\SDK\Assemblies\Microsoft.AnalysisServices.DLL to access the Server, Database and
DataSource classes.
class ConnectivityTests
{
// Variables
String serverName = "";
String databaseName = "";
String dataSourceName = "";
[Test]
public void TestDataSourceConnection()
{
// Creates an instance of the Server
Server server = new Server();
server.Connect(serverName);
// Gets the Database from the Server
Database database = server.Databases[databaseName];
// Get the DataSource from the Database
DataSource dataSource = database.DataSources.FindByName(dataSourceName);
// Attempt to open a connection to the dataSource. Fail test if unsuccessful
OleDbConnection connection = new OleDbConnection(dataSource.ConnectionString);
try
{
connection.Open();
}
catch (OleDbException e)
{
Assert.Fail(e.ToString());
}
finally
{
connection.Close();
}
}
I believe that this test is sufficient for my testing (Once I've added some more try..catch blocks and Assertions). If the test passes, it means there are no connectivity issues between my machine and both servers, which implies that there shouldn't be any connectivity issues between the servers.
However, I have been unable to work out how to test the connection between the two servers directly and I am interested if anyone knows a way of doing this.
The best solution I have come across to doing this connectivity test is below:
Please note that this requires the Microsoft.AnalysisServices.DLL to be added as a reference.
class ConnectivityTests
{
// Variables
String serverName = "";
String databaseName = "";
String dataSourceName = "";
[Test]
public void TestDataSourceConnection()
{
try
{
// Creates an instance of the Server
Server server = new Server();
server.Connect(serverName);
// Gets the Database from the Server
Database database = server.Databases[databaseName];
// Get the DataSource from the Database
DataSource dataSource = database.DataSources.FindByName(dataSourceName);
// Attempt to open a connection to the dataSource. Fail test if unsuccessful
OleDbConnection connection = new OleDbConnection(dataSource.ConnectionString);
connection.Open();
}
catch (Exception e)
{
Assert.Fail(e.ToString());
}
finally
{
connection.Close();
}
}
}

C# IIS 7.5 class not registered exception

We just started up a new webserver and i'm running into "class not registered" when creating a new application pool. I'm using the code below but I have no idea how to distinguish what is not registered. Any thoughts would be awesome.
Thanks.
string path = "IIS://" + server + "/W3SVC";
string app_pools_path = path + "/AppPools";
/error below.
var app_pools = new DirectoryEntry(app_pools_path);
foreach (DirectoryEntry app_pool in app_pools.Children)
{
//do work
}
Error "Class no registered" error code:2147221164
ON the server open the server manager
add new features ==> Web Server (IIS) ==> Management Tools ==> IIS 6 Management Compatibility then check IIS6 Metabase Compatibility. use your original connection string / path
string path = "IIS://" + server + "/W3SVC";
string app_pools_path = path + "/AppPools";
try this please :
private void StopAppPool(string app_Pool , string server)
{
try
{
ConnectionOptions co = new ConnectionOptions();
co.Username = "DomainName\\UserName";
co.Password = "UserPassword";
string appPool = "W3SVC/AppPools/" + app_Pool;
co.Impersonation = ImpersonationLevel.Impersonate;
co.Authentication = AuthenticationLevel.PacketPrivacy;
string objPath = "IISApplicationPool.Name='" + appPool + "'";
ManagementScope scope = new ManagementScope(#"\\" + server + #"\root\MicrosoftIISv2", co);
using (ManagementObject mc = new ManagementObject(objPath))
{
mc.Scope = scope;
mc.InvokeMethod("Stop", null, null);
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
Console.WriteLine(e.StackTrace);
Console.WriteLine(e.InnerException);
Console.WriteLine(e.Data);
}
//Console.ReadLine();
}
You should avoid using DirectoryEntry to manipulate IIS 7 and above. That's the old API based on IIS ADSI interfaces,
http://msdn.microsoft.com/en-us/library/ms524896(v=vs.90).aspx
IIS 6 Compatibilities might help you out though,
http://blogs.msdn.com/b/narahari/archive/2009/05/13/when-using-directoryservices-to-access-iis-schema-iis6-management-compatibility-pack-needs-to-be-installed-system-runtime-interopservices-comexception-0x80005000.aspx
The best solution (which is also strong typed and more convenient for C# developers) is Microsoft.Web.Administration,
http://www.iis.net/learn/manage/scripting/how-to-use-microsoftwebadministration

Categories

Resources