I have a windows application that write with c# 4. in this windows application i get user name, password, server IP and etc from user and create a oracle connection string from this inputs and test connect to database by this code:
private OperationStatus CheckConnectToOracleDatabase(string connectionString)
{
var oracleConnection = new OracleConnection();
try
{
oracleConnection.ConnectionString = connectionString;
oracleConnection.Open();
oracleConnection.Close();
return new OperationStatus { Status = true };
}
catch (OracleException ex)
{
return new OperationStatus { Status = false, ExceptionMessage = ex.Message };
}
catch (Exception ex)
{
return new OperationStatus { Status = false, ExceptionMessage = ex.Message };
}
finally
{
if (oracleConnection.State != ConnectionState.Closed)
oracleConnection.Close();
}
}
In my platform everything is OK and test is successful, but in the platform of customer and error was happened, this error was shown in below picture:
my platform is win server 2003, and platform of customer is win 7 32bit.
Related
AuthController - Authenticate action
[HttpPost("authenticate")]
public async Task<ActionResult<Login>> Authenticate([FromBody] Login login)
{
// login will come in from the device with basic auth
var c = 0;
string token = string.Empty;
try
{
bool isAuth = _unitOfWork.Logins.GetAuthenticateUser(username, password);
if(isAuth == false)
{
var msg = "Authentication Failed";
login.Message = msg;
return new JsonResult(login);
}
Jwt j = new Jwt(_unitOfWork);
try
{
login.Token = j.CreateToken(username);
SessionModel session = new SessionModel();
session.SessionStart = DateTime.Now;
login.SessionStart = session.SessionStart;
session.UserName = username;
session.Token = login.Token;
await _unitOfWork.Sessions.AddAsync(session);
}
catch (Exception ex)
{
//delete session if there is jwt error
var msg = $"Error message from create token - Inner Exception: {ex.InnerException} Exception Message: {ex.Message} Source: {ex.Source}";
return UnAuthorized;
}
}
catch (Exception ex)
{
var msg = $"Error message from Header Auth decode - Inner Exception: {ex.InnerException} Exception Message: {ex.Message} Source: {ex.Source}";
login.Message = msg;
return new JsonResult(login);
}
//return login obj with token, msg, session datetime
return new JsonResult(login);
}
The above code all runs as expected until it reached the line at the end
return new JsonResult(login);
At that point Visual Studio exits debugging in IIS Express without warning or error.
I am testing the api with Postman.
When I execute in Postman, I get a status 200 but I do not get the expected Json result. That is at the point where Visual Studio drops out and terminates the debugging session.
I use a VPN class in my program. But when I try to connect, it cause the following error:
the system could not find the phone book entry for this connection
Here is the connect method:
public void VPN_Connect(string VPN_Name, string VPN_ID, string VPN_PW)
{
string path = System.Environment.GetFolderPath(System.Environment.SpecialFolder.ApplicationData) + #"\Microsoft\Network\Connections\Pbk\rasphone.pbk";
AllUsersPhoneBook = new RasPhoneBook();
AllUsersPhoneBook.Open(path);
if (AllUsersPhoneBook.Entries.Contains(EntryName))
{
AllUsersPhoneBook.Entries[EntryName].PhoneNumber = VPN_Name;
AllUsersPhoneBook.Entries[EntryName].Update();
}
else
{
RasEntry entry = RasEntry.CreateVpnEntry(EntryName, VPN_Name, RasVpnStrategy.Default,
RasDevice.GetDeviceByName("(PPTP)", RasDeviceType.Vpn));
entry.EncryptionType = RasEncryptionType.None;
AllUsersPhoneBook.Entries.Add(entry);
}
Dialer = new RasDialer();
Dialer.DialCompleted += new EventHandler<DialCompletedEventArgs>(Dialer_DialCompleted);
this.Dialer.EntryName = EntryName;
this.Dialer.PhoneBookPath = RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.AllUsers);
try
{
this.Dialer.Credentials = new NetworkCredential(VPN_ID, VPN_PW);
this.handle = this.Dialer.DialAsync();
VPN_Status = (int)status.Defalut;
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
How can I solve this problem?
I'm also using windows 10 with latest update and DotRas last version.
Trying to create functions to programmatically add a password to the sqlite database, and remove it - to get rid of the password when in debug.
I followed the steps of the best post explaining it (https://stackoverflow.com/a/1385690/6617804) and all the other sources that I found are using the same process.
What I am doing:
The connection strings:
private static string AuthoringDbFullPath = System.IO.Path.Combine(DataFolder, "Authoring.db");
private static string AuthoringConnectionStringWithPw = #"Data Source=" + AuthoringDbFullPath + "; Password=" + DbPassword +";";
private static string AuthoringConnectionStringWithoutPw = #"Data Source=" + AuthoringDbFullPath+";";
private static string AuthoringConnectionString = AuthoringConnectionStringWithPw;
The enable password function:
public static bool EnableDbPassword()
{
try
{
//The Connection must not open closed to set a password
Connection = new SQLiteConnection(AuthoringConnectionStringWithoutPw);
Connection.SetPassword(DbPassword);
Connection = new SQLiteConnection(AuthoringConnectionStringWithPw);
Connection.Open();
Connection.Close();
if (Connection != null && Connection?.State == System.Data.ConnectionState.Open)
{
Connection.SetPassword(DbPassword);
AuthoringConnectionString = AuthoringConnectionStringWithPw;
return true;
}
}
catch (Exception ex)
{
LogManager.LogException(ex);
}
return false;
}
The disable password function:
public static bool DisableDbPassword()
{
try
{
//if not connected, it does
if (Connection == null || Connection?.State != System.Data.ConnectionState.Open)
{
Connection = new SQLiteConnection(AuthoringConnectionStringWithPw);
Connection.Open();
}
Connection.Close();
Connection.Open();
if (Connection != null && Connection?.State == System.Data.ConnectionState.Open)
{
Connection.ChangePassword("");
AuthoringConnectionString = AuthoringConnectionStringWithoutPw;
return true;
}
}
catch (Exception ex)
{
LogManager.LogException(ex);
}
return false;
}
Two things happening:
After having add the password (with no apparent issue), I can still open the database in SQLiteStudio as if there were still no password:
When trying to disable after having enabled it, it raised a System.Data.SQLite.SqliteException exception when executing Connection.ChangePassword("");
System.Data.SQLite.SqliteException :
Message "file is not a database. not an error
How to create a simple architecture being able to add and remove a password on a SQLite database?
I'm working on a Silverlight application that uses oracle security to authenticate the users. (This is a business requirement so it can't be changed).
I do so by calling a WCF web service that attempts to open a connection to the database using the provided username and password. If the connection fails, I catch the exception and return a message to the user, here's the login code:
[OperationContract]
public LoginResult LogIn(string username, string password, DateTime preventCache)
{
var result = new List<string>();
try
{
connectionString = ConfigurationManager.ConnectionStrings["SecurityBD"].ToString();
connectionString = connectionString.Replace("[username]", username);
connectionString = connectionString.Replace("[password]",passowrd)
using (var connection = new Oracle.DataAccess.Client.OracleConnection())
{
connection.ConnectionString = connectionString;
connection.Open();
if (connection.State == System.Data.ConnectionState.Open)
{
connection.Close();
return new LoginResult(true, GetPermisos(username), preventCache);
}
else
{
return new LoginResult(false, null, preventCache);
}
}
}
catch (Oracle.DataAccess.Client.OracleException ex)
{
if (ex.Number == 1017)
{
return new LoginResult(new SecurityError("Wrong credentials.", ErrorType.InvalidCredentials));
}
//Password expired.
if (ex.Number == 28001)
{
return new LoginResult(new SecurityError("Password expired.", ErrorType.PasswordExpired));
}
//Acount is locked.
if (ex.Number == 28000)
{
return new LoginResult(new SecurityError("Account is locked.", ErrorType.AccountLocked));
}
else
{
return new LoginResult(new SecurityError("An error occurred while attempting to connect." + Environment.NewLine + "Error: " + ex.ToString(), ErrorType.UndefinedError));
}
}
catch (Exception exg)
{
return new LoginResult(new SecurityError("An error occurred while attempting to connect." + Environment.NewLine + "Error: " + exg.ToString(), ErrorType.UndefinedError));
}
}
If the connection fails because of an expired password, I show the corresponding message to the user and then prompt him for his old and new password, and then send the new credentials to a ChangePassword method on my web serivce.
[OperationContract]
public ChangePasswordResult ChangePassword(string username, string oldPasswrod, string newPassword)
{
string connectionString = string.Empty;
try
{
connectionString = ConfigurationManager.ConnectionStrings["SecurityBD"].ToString();
connectionString = connectionString.Replace("[username]", username);
connectionString = connectionString.Replace("[password]",passowrd)
using (var connection = new OracleConnection(connectionString))
{
connection.Open();
if (connection.State == System.Data.ConnectionState.Open)
{
connection.Close();
using (var newConnection = new Oracle.DataAccess.Client.OracleConnection(connectionString))
{
newConnection.OpenWithNewPassword(Cryptography.TransportDecrypt(newPassword));
if (newConnection.State == System.Data.ConnectionState.Open)
{
return new ChangePasswordResult(null);
}
}
}
return new ChangePasswordResult(new SecurityError("Couldn't connect to the database.", ErrorType.UndefinedError));
}
}
catch (OracleException ex)
{
if (ex.Number == 1017)
{
return new ChangePasswordResult(new SecurityError("Wrong password", ErrorType.InvalidCredentials));
}
//Password expired.
if (ex.Number == 28001)
{
using (var newConnection = new Oracle.DataAccess.Client.OracleConnection(connectionString))
{
try
{
newConnection.OpenWithNewPassword(Cryptography.TransportDecrypt(newPassword));
if (newConnection.State == System.Data.ConnectionState.Open)
{
return new ChangePasswordResult(null);
}
else
{
return new ChangePasswordResult(new SecurityError("No se pudo establecer una conexión con la base de datos", ErrorType.UndefinedError));
}
}
catch (Oracle.DataAccess.Client.OracleException oex)
{
if (oex.Number == 28003)
return new ChangePasswordResult(new SecurityError("You'r new password does not match the security requeriments.." + Environment.NewLine + oex.Message, ErrorType.PasswordNotChanged));
else
return new ChangePasswordResult(new SecurityError(oex.Message, ErrorType.UndefinedError));
}
}
}
//Acount is locked.
if (ex.Number == 28000)
{
return new ChangePasswordResult(new SecurityError("Account is locked.", ErrorType.AccountLocked));
}
else
{
return new ChangePasswordResult(new SecurityError("Couldn't establish a connection." + Environment.NewLine + "Error: " + ex.Message, ErrorType.UndefinedError));
}
}
catch
{
throw;
}
}
After I perform the change password operation, the user is still able to connect with the old password and he's not able to connect with the new password. Only after I restart the application the change seems to take effect.
I'm using oracle's ODP.net driver. With Microsoft's oracle client, the user is able to connect with both the new and the old password after the password change.
The preventCache parameter was there only to verify that there was no type of client cache. I send the current date from the client, and then return the same value from the web service to see if it actually changes with subsequent requests, and it does as expected.
I've tried listening to the InfoMessage event of the connection, to see if there's any warning, but doing this prevents the password expired exception from being risen, and the code never reaches the eventHandler.
I'm completely lost, this behavior seems very odd to me and I still haven't figured out the root cause for the problem.
I've tryied copying the LogIn and ChangePassword methods on a desktop (WPF) application and it behaves exactly the same. So i guess the problem is not in the silverlight client.
Ok, i've figured this out. Checking with Toad the connection reminded opend even after executing the Connection.Close() method. This behavior seems to be part of the connection pooling mechanism from oracle.
Including Pooling=false on the connection string solved the problem.
I want to add a new user to newly created database and if this user exists then i will connect to that database.
My code is:
public CreateDatabaseOperationResult CreateDatabase(string databaseName,string username,string password, MongoServer server)
{
CreateDatabaseOperationResult createDatabaseOpResult = new CreateDatabaseOperationResult();
string message = null;
MongoCredentials credentials = new MongoCredentials(username, password);
MongoUser user = new MongoUser(credentials, false);
try
{
if (IsDatabaseNameValid(databaseName, out message))
{
if (server.DatabaseExists(databaseName, admincredentials) == true)
{
createDatabaseOpResult.Database = server.GetDatabase(databaseName, credentials);
MongoUser tempuser = createDatabaseOpResult.Database.FindUser(username);
if (tempuser.Equals(user))
{
//createDatabaseOpResult.DatabaseExists = true;
createDatabaseOpResult.IsOperationSuccessfull = false;
throw new ArgumentException("Database Already exist with different set of credentials ");
}
}
else
{
createDatabaseOpResult.Database = server.GetDatabase(databaseName, credentials);
createDatabaseOpResult.Database.AddUser(user);
//createDatabaseOpResult.DatabaseExists = false;
}
createDatabaseOpResult.IsOperationSuccessfull = true;
}
}
catch (MongoQueryException ex)
{
createDatabaseOpResult.Error = ex;
}
//catch (MongoAuthenticationException ex)
//{
// createDatabaseOpResult.Error = ex;
//}
catch (MongoException ex)
{
createDatabaseOpResult.Error = ex;
}
catch (ArgumentException ex)
{
createDatabaseOpResult.Error = ex;
}
return createDatabaseOpResult;
}
When i use the existing database it connects to that database but when i try to add new use Database.AddUser gives error 'invalid credentials for this database'
Please see the error and reply
Most people use the mongo shell to add and remove users, but if you really want to do it in C# the trick is to use the right credentials depending on what you are trying to do. Assume you have the following two sets of credentials, one for the admin database and one for regular databases:
var adminCredentials = new MongoCredentials("myadminusername", "myadminpassword", true);
var userCredentials = new MongoCredentials("myusername", "myuserpassword");
Note that when creating the adminCredentials you must pass true to the admin parameter.
To test if a database exists requires admin credentials:
if (server.DatabaseExists("mydatabase", adminCredentials))
{
// database exists
}
To add a user requires admin credentials:
var myDatabaseWithAdminCredentials = server.GetDatabase("mydatabase", adminCredentials);
if (myDatabaseWithAdminCredentials.FindUser("myusername") == null)
{
myDatabaseWithAdminCredentials.AddUser(userCredentials);
}
Normally you use regular user credentials to work with a database:
var myDatabaseWithUserCredentials = server.GetDatabase("mydatabase", userCredentials);
var count = myDatabaseWithUserCredentials.GetCollection("mycollection").Count();
Also, keep in mind that each database can have any number of users, so you don't really need to be checking whether the database already exists with a different set of credentials.