I am building an application which has a database on the server machine and I am using this method for database access:
public static string GetDefaultConnectionString()
{
//get my db info from ini file
dbinfo DatabaseInfo = new dbinfo();
DatabaseInfo = GetDatabaseInfo();
if (DatabaseInfo.dbName == "" || DatabaseInfo.Password == "" || DatabaseInfo.Server == "" || DatabaseInfo.UserId == "")
{
throw new Exception("Database config file is not valid");
}
else
{
MessageBox.Show("Db name " + DatabaseInfo.dbName);
MessageBox.Show("User " + DatabaseInfo.UserId);
MessageBox.Show("Db Pass " + DatabaseInfo.Password);
MessageBox.Show("Db Server " + DatabaseInfo.Server);
}
string conStrIntegratedSecurity = new System.Data.EntityClient.EntityConnectionStringBuilder
{
Metadata = "res://*/Model1.csdl|res://*/Model1.ssdl|res://*/Model1.msl",
Provider = "System.Data.SqlClient",
ProviderConnectionString = new System.Data.SqlClient.SqlConnectionStringBuilder
{
InitialCatalog = DatabaseInfo.dbName,
DataSource = DatabaseInfo.Server,
IntegratedSecurity = true,
UserID = DatabaseInfo.UserId,
Password = DatabaseInfo.Password,
MultipleActiveResultSets = true,
ConnectTimeout = 0,
MaxPoolSize = 500,
}.ConnectionString
}.ConnectionString;
//MessageBox.Show(conStrIntegratedSecurity);
return conStrIntegratedSecurity;
}
and it works fine in server pc.
But, when I install this application on any client machine, it cannot open a connection and it gives the following error message:
System.Data.EntityException: The underlying provider failed on Open. --->
System.Data.SqlClient.SqlException: Cannot open database "dbName" requested by the login. The login failed.
Login failed for user 'ServerName\User'.
Does anyone know why this is happening?
I just use
IntegratedSecurity = true,
to
IntegratedSecurity = false,
and it works!
Related
I am developing a WebService in C # however I am facing an error.
This is the error :
System.Security.Authentication.AuthenticationException: A call to SSPI failed, see inner exception. ---> System.ComponentModel.Win32Exception: The message or signature supplied for verification has been altered
So I sometimes get this error when I open my MySQL connection in my WebService.
I had this error by launching my webService twice at the same time then I tried again and no more errors.
My web service is on a Windows server 2012 R2 and i'm using .NET Framework 4.7.2 (It is called by the website php).
I did quite a bit of internet research and came across this in C# :
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
But it doesn't work, Do you have any idea so that I do not face this problem again ?
There is my MySQL open connection method :
public MySqlConnection OpenConnectionDB(string clientId)
{
listVerifs = new List<string>();
int iConn = 0;
try
{
MySqlConnection sqlCo = new MySqlConnection("server=MyServer;database=" + this.db + ";username=MyUID;password=MyPwd;AllowLoadLocalInfile=true");
if (sqlCo.State != ConnectionState.Open)
{
sqlCo.Open();
}
listVerifs.Add("CO SQL");
dataSourceDBF = #"//ntserver/Winbooks_Data/winbooks/data/" + clientId + "/";
dbfCo = new AdsConnection(#"data Source=//ntserver/Winbooks_Data/winbooks/data/" + clientId + "/" + clientId + ".add;User ID=mYUID;Password=;ServerType=local;ReadOnly=true;pooling=true;TrimTrailingSpaces=true;TableType=CDX;LockMode=COMPATIBLE");
if (dbfCo.State == ConnectionState.Closed)
{
dbfCo.Open();
}
listVerifs.Add("CO DBF");
Console.WriteLine("Databases connections open succesfull");
return sqlCo;
}
catch (Exception e)
{
dbfCo = null;
Console.WriteLine("Error connection " + e.Message);
test = e.Message;
log.AddLog("Erreur Fonction OpenConnectionDB : " + e.ToString(), 3, "WebServiceMySQL");
return null;
}
Thank's in advance !
hello people i don't know if i am askin properly but i have a big probleme i am new in programming i hope u can help me.
i created an asmx that execute a xmla query on analysis services so evrything is runing perfect when i try it in local but when i deployed on iis in a windows server 2008 r2 and i tested it generated me an error "A connection cannot be made. Ensure that the server is running" can you please guys help me with that i will appreciat it.
"Sorry if my english is bad".
[SoapRpcMethod()]
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public String StartJob(String JobId)
{
string res = "";
string chronomark = (DateTime.Now).ToString("yyy-MM-dd_HHmmss");
String logFile = System.Configuration.ConfigurationManager.AppSettings["log"] + (JobId != null ? JobId : "null") + chronomark + ".log";
try
{
FileStream fs = new FileStream(logFile, FileMode.CreateNew);
StreamWriter swr = new StreamWriter(fs);
try
{
try
{
if (JobId == null) throw new Exception("NO JOB ID GIVEN");
Regex rgx = new Regex("^[0-9A-Z-]{32}$");
if (!rgx.IsMatch(JobId)) throw new Exception("BAD JOB ID");
MatchCollection mcol = rgx.Matches(JobId);
if (mcol.Count != 1) throw new Exception("BAD JOB ID Collection");
String sJobID = mcol[0].Value;
FileInfo fi = new FileInfo(System.Configuration.ConfigurationManager.AppSettings["storage"] + sJobID + ".cube");
if (!fi.Exists)
throw new Exception("NO REGISTRED JOB ID");
FileStream fstr;
try
{
fstr = fi.OpenRead();
}
catch (Exception ex)
{
swr.WriteLine(ex.ToString());
swr.WriteLine(ex.StackTrace);
throw new Exception("NO JOB ID REGISTRED");
}
StreamReader sr = new StreamReader(fstr);
String sTargetServer = sr.ReadLine();
StringBuilder sbrXMLA = new StringBuilder();
sbrXMLA.Append(sr.ReadToEnd());
sr.Close();
fstr.Close();
swr.WriteLine(sbrXMLA.ToString());
swr.WriteLine(sTargetServer);
res = sendXMLARequest(sbrXMLA.ToString(), sTargetServer, swr);
return res;
}
catch (Exception se)
{
swr.WriteLine(se.ToString());
swr.WriteLine(se.StackTrace);
res = "ERROR :" + se.Message.ToString();
return res;
}
}
finally
{
swr.Flush();
fs.Close();
}
}
catch(Exception exp)
{
res = "ERROR : " + exp.Message;
return res;
}
}
[WebMethod]
private String sendXMLARequest(String sXMLARequest, String sTargetServer, StreamWriter logger)
{
XmlDocument doc = new XmlDocument();
doc.LoadXml(sXMLARequest);
String Json = JsonConvert.SerializeXmlNode(doc);
Server server = new Server();
server.Connect(#"Provider=OLAP;Data Source=" + sTargetServer);
server.Execute(sXMLARequest);
string con = server.Connected.ToString();
XmlaResultCollection rsCollection = server.Execute(sXMLARequest);
String s = null;
foreach (XmlaResult res in rsCollection)
{
s += res.Value.ToString();
foreach (XmlaMessage message in res.Messages)
{
logger.WriteLine(message.ToString());
if (message is XmlaError)
Json = s + "ERROR : " + message.Description;
else
Json = s + "WARNIN : " + message.Description;
}
}
server.Disconnect();
JavaScriptSerializer js = new JavaScriptSerializer();
return js.Serialize(Json);
}
A possible reason: Lack of access to the IIS process to the SSAS server.
(1) Determine you IIS application pool identity
(2) Give permission to this user in SSAS
Additionally:
(1) How is your web service call authenticated (anonymous / windows authentication / etc) ?
(2) Look at the msmdsrv.log file in SSAS folder
See whether this related SO post helps:
Either the user, 'IIS APPPOOL\App Name', does not have access to the 'SSAS Cube Name' database, or the database does not exist
I was trying to use SSH tunneling to access my MySQL database using C# but I'm getting an exception
Unable to connect to any of the specified MySQL hosts.
I got this code with the help of this:
C# SSH tunnel to MySQL server
Here is my code:
PasswordConnectionInfo connectionInfo = new PasswordConnectionInfo("example.com", 2222, "username", "password");
connectionInfo.Timeout = TimeSpan.FromSeconds(30);
using (var client = new SshClient(connectionInfo))
{
try
{
Console.WriteLine("Trying SSH connection...");
client.Connect();
if (client.IsConnected)
{
Console.WriteLine("SSH connection is active: {0}", client.ConnectionInfo.ToString());
}
else
{
Console.WriteLine("SSH connection has failed: {0}", client.ConnectionInfo.ToString());
}
Console.WriteLine("\r\nTrying port forwarding...");
var portFwld = new ForwardedPortLocal(IPAddress.Loopback.ToString(),2222, "example.com", 3306);
client.AddForwardedPort(portFwld);
portFwld.Start();
if (portFwld.IsStarted)
{
Console.WriteLine("Port forwarded: {0}", portFwld.ToString());
Console.WriteLine("\r\nTrying database connection...");
DBConnect dbConnect = new DBConnect("127.0.0.1", "database", "username", "password", "3306");
int id = dbConnect.Count("table");
MessageBox.Show(id + " count ");
}
else
{
Console.WriteLine("Port forwarding has failed.");
}
}
catch (SshException ex)
{
Console.WriteLine("SSH client connection error: {0}", ex.Message);
}
catch (System.Net.Sockets.SocketException ex1)
{
Console.WriteLine("Socket connection error: {0}", ex1.Message);
}
}
private MySqlConnection connection;
private string server;
public string Server
{
get
{
return this.server;
}
set
{
this.server = value;
}
}
private string database;
public string Database
{
get
{
return this.database;
}
set
{
this.database = value;
}
}
private string uid;
public string Uid
{
get
{
return this.server;
}
set
{
this.server = value;
}
}
private string password;
public string Password
{
get
{
return this.password;
}
set
{
this.password = value;
}
}
private string port;
public string Port
{
get
{
return this.port;
}
set
{
this.port = value;
}
}
//Constructor
public DBConnect(string server, string database, string uid, string password, string port = "3306")
{
this.server = server;
this.database = database;
this.uid = uid;
this.password = password;
this.port = port;
Initialize();
}
//Initialize values
private void Initialize()
{
string connectionString;
connectionString = "SERVER=" + server + ";" + "DATABASE=" + database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";";
connection = new MySqlConnection(connectionString);
}
//open connection to database
private bool OpenConnection()
{
try
{
connection.Open();
Console.WriteLine("MySQL connected.");
return true;
}
catch (MySqlException ex)
{
//When handling errors, you can your application's response based on the error number.
//The two most common error numbers when connecting are as follows:
//0: Cannot connect to server.
//1045: Invalid user name and/or password.
switch (ex.Number)
{
case 0:
Console.WriteLine("Cannot connect to server. Contact administrator");
break;
case 1045:
Console.WriteLine("Invalid username/password, please try again");
break;
default:
Console.WriteLine("Unhandled exception: {0}.", ex.Message);
break;
}
return false;
}
}
//Close connection
private bool CloseConnection()
{
try
{
connection.Close();
return true;
}
catch (MySqlException ex)
{
Console.WriteLine(ex.Message);
return false;
}
}
//Count statement
public int Count(string tableName)
{
string query = "SELECT Count(*) FROM " + tableName;
int Count = -1;
//Open Connection
if (this.OpenConnection() == true)
{
//Create Mysql Command
MySqlCommand cmd = new MySqlCommand(query, connection);
//ExecuteScalar will return one value
Count = int.Parse(cmd.ExecuteScalar() + "");
//close Connection
this.CloseConnection();
return Count;
}
return Count;
}
The output that I got in my console is:
Trying SSH connection...
A first chance exception of type 'System.ObjectDisposedException' occurred in mscorlib.dll
A first chance exception of type 'System.ObjectDisposedException' occurred in System.dll
SSH connection is active: Renci.SshNet.PasswordConnectionInfo
Trying port forwarding...
Port forwarded: Renci.SshNet.ForwardedPortLocal
A first chance exception of type 'Renci.SshNet.Common.SshConnectionException' occurred in Renci.SshNet.dll
Trying database connection...
A first chance exception of type 'System.Net.Sockets.SocketException' occurred in System.dll
A first chance exception of type 'System.Net.Sockets.SocketException' occurred in MySql.Data.dll
A first chance exception of type 'MySql.Data.MySqlClient.MySqlException' occurred in MySql.Data.dll
A first chance exception of type 'MySql.Data.MySqlClient.MySqlException' occurred in MySql.Data.dll
Error: 0 : Unable to connect to any of the specified MySQL hosts.
A first chance exception of type 'MySql.Data.MySqlClient.MySqlException' occurred in MySql.Data.dll
A first chance exception of type 'MySql.Data.MySqlClient.MySqlException' occurred in MySql.Data.dll
Unhandled exception: Unable to connect to any of the specified MySQL hosts..
UPATE:
I have changed the port forwarding settings to :
var portFwld = new ForwardedPortLocal("127.0.0.1", 1000, "127.0.0.1", 3306);
and I have changed my mySQL String to :
connectionString = "server=127.0.0.1;port=1000; UID=username; password=password; database=data1; charset=utf8;Allow User Variables=True";
I'm being connected to the ssh and my port is forwarded but I still can't connect to MySQL database, I'm getting an exception:
A first chance exception of type 'System.IO.EndOfStreamException' occurred in MySql.Data.dll
A first chance exception of type 'MySql.Data.MySqlClient.MySqlException' occurred in MySql.Data.dll
A first chance exception of type 'MySql.Data.MySqlClient.MySqlException' occurred in MySql.Data.dll
Error: 0 : Reading from the stream has failed.
You have to connect the MySQL to the bound port of the forwarding. I.e. to the 2222.
Or even more semantically correct, use portFwld.BoundPort. Equivalently, use portFwld.BoundHost.
DBConnect dbConnect = new DBConnect(portFwld.BoundHost, "database", "username", "password", portFwld.BoundPort);
Also note that it makes more sense to refer to the MySQL host as "localhost", rather than the "example.com", as the hostname is resolved on the server-side. And when on the server side, you typically won't connect to "example.com", but to a "localhost".
var portFwld = new ForwardedPortLocal(IPAddress.Loopback.ToString(), 2222, "localhost", 3306);
And of course you need to keep the SSH session open while you need the tunnel. So you have to connect to the DB within the using block:
using (var client = new SshClient(connectionInfo))
{
...
client.Connect();
...
portFwld.Start();
...
DBConnect dbConnect = new DBConnect(portFwld.BoundHost, "database", "username", "password", portFwld.BoundPort);
}
I am executing below code successfully without any errors but when I am executing list_queue command it gives me no queue. Dont know where the problem is.
The below code is not giving error at all. My machine is windows 7 64x, installed AMPQ runtime 64bit and using 32x RabbitMq server v.2.8.1 .
private void createExchange(string message)
{
var queName = Convert.ToString(ConfigurationManager.AppSettings["clientQueue"]);
var exchangeName = Convert.ToString(ConfigurationManager.AppSettings["clientExchange"]);
var hostName = Convert.ToString(ConfigurationManager.AppSettings["host"]);
_logger.Info("entered in create exchange");
_logger.Info("queName: " + queName);
_logger.Info("exchangeName: " + exchangeName);
_logger.Info("hostName: " + hostName);
try
{
var connectionFactory = new ConnectionFactory();
connectionFactory.HostName = "localhost";
connectionFactory.UserName = "user1";
connectionFactory.Password = "userpassword";
using (IConnection connection =
connectionFactory.CreateConnection())
{
_logger.Info("Conncection created");
using (IModel model = connection.CreateModel())
{
_logger.Info("Model is created");
model.ExchangeDeclare(exchangeName, ExchangeType.Fanout, true);
model.QueueDeclare(queName, true, true, false, null);
model.QueueBind(queName, exchangeName, "", new Dictionary<string, object>());
IBasicProperties basicProperties = model.CreateBasicProperties();
model.BasicPublish(exchangeName, "", false, false,
basicProperties, Encoding.UTF8.GetBytes(message));
_logger.Info("message: " + message);
_logger.Info("message published");
}
}
}
catch(Exception ex)
{
_logger.Info("Error in create exchange");
_logger.Info("InnerException:" + ex.InnerException);
_logger.Info("Message:" + ex.Message);
_logger.Info("StackTrace:" + ex.StackTrace);
}
}
It appears as though you are declaring an 'exclusive' queue. Exclusive queues are exclusive to the connection and as such cannot be operated upon (including being listed) from another connection.
Try
Model.QueueDeclare(queName, true, **false**, false, null)
If you want to be able to list it or do anything else with if from another connection.
I'm trying to user Redemption to update a user's Outlook contacts. The user I'm affecting is passed in the exchangeUser, call him "Target User".
This code works when I run it logged in as myself:
public OutlookFolders(string outlookRootFolder, string exchangeUser, string mailServer)
{
var session = new RDOSessionClass();
session.LogonExchangeMailbox(exchangeUser, mailServer);
session.Stores.FindExchangePublicFoldersStore();
var store = session.GetSharedMailbox(exchangeUser);
//...
}
I tried to log in as a 3rd user "Test User" who is not me and is not "Target User". My program brings up a password prompt at runtime when it gets to FindExchangePublicFoldersStore, and if I don't fill in my credentials it fails with the error:
System.Runtime.InteropServices.COMException (0x8004011D): Error in
IMAPISession.OpenMsgStore(pbExchangeProviderPrimaryUserGuid):
MAPI_E_FAILONEPROVIDER
ulVersion: 0
Error: Microsoft Exchange is not available. Either there are network
problems or the Exchange computer is down for maintenance.
Component: Microsoft Exchange Information Store
ulLowLevelError: 2147746069
ulContext: 1318
I tried giving "Test User" owner permission on "Target User's" Mailbox and Contacts folder. Doesn't seem to make a difference. What other permissions need to be set for this to work?
The rule of thumb is to run your code as a user who can access the mailboxes in question, call LogonExchangeMailbox for the current user, then open other users' mailboxes using GetSharedMailbox.
Here's the code for Dmitry's answer.
It also uses a function from Milan's blog.
public OutlookFolders(string exchangeUser, string mailServer)
{
var session = new RDOSessionClass();
var userFullName = GetFullName("DOMAIN-NT\\" + Environment.UserName);
session.LogonExchangeMailbox(userFullName, mailServer);
session.Stores.FindExchangePublicFoldersStore();
var store = session.GetSharedMailbox(exchangeUser);
rootFolder = store.GetDefaultFolder((rdoDefaultFolders)OlDefaultFolders.olFolderContacts);
}
public static string GetFullName(string strLogin)
{
string str = "";
string strDomain;
string strName;
// Parse the string to check if domain name is present.
int idx = strLogin.IndexOf('\\');
if (idx == -1)
{
idx = strLogin.IndexOf('#');
}
if (idx != -1)
{
strDomain = strLogin.Substring(0, idx);
strName = strLogin.Substring(idx + 1);
}
else
{
strDomain = Environment.MachineName;
strName = strLogin;
}
DirectoryEntry obDirEntry = null;
try
{
obDirEntry = new DirectoryEntry("WinNT://" + strDomain + "/" + strName);
PropertyCollection coll = obDirEntry.Properties;
object obVal = coll["FullName"].Value;
str = obVal.ToString();
}
catch (System.Exception ex)
{
str = ex.Message;
}
return str;
}