Getting all the events from a remote computer - c#

I have a problem with getting all the events from a remote computer.
try
{
string queryString = "*[System/Level=1 or System/Level=2 or System/Level=3 or System/Level=4 or System/Level=5]";
SecureString password = new NetworkCredential("", getPassword()).SecurePassword;
EventLogSession session = new("RemoteComputer", getDomainName(), getAdminName(), password, SessionAuthentication.Default);
password.Dispose();
EventLogQuery query = new("Application", PathType.LogName, queryString);
query.Session = session;
EventLogReader logReader = new(query);
EventRecord eventRecord;
while ((eventRecord = logReader.ReadEvent()) != null)
{
eventRecords.Add(eventRecord); //save records
}
//display records
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
The program is getting only some part of events from the remote computer and displays them, but then it throws an exception with message "Cannot find the specified file".
What's the problem and how can I get all the events?

Related

asp.net core webapi - debugging unexpectedly shuts off in IIS Express

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.

C# Dapper How to know query is correct

I am making a login form using dapper library something is wrong here i cant seem to make it to work even if the password or username is wrong it opens up new form
if (string.IsNullOrEmpty(txtUsername.Text))
{
MessageBox.Show("Please enter your usernmae.", "Message", MessageBoxButtons.OK, MessageBoxIcon.Warning);
txtUsername.Focus();
return;
}
try
{
using (IDbConnection db = new SqlConnection(ConfigurationManager.ConnectionStrings["cn"].ConnectionString))
{
var data = db.Query("select Username,Password from UserLog", commandType: CommandType.Text);
if ((data.SingleOrDefault() !=null)
{
MessageBox.Show("You have been succesfully logged in.", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
FormHome frm= new FormHome();
frm.ShowDialog();
this.Close();
}
else
{
MessageBox.Show("Your Username or Password is Incorrect.", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
You are simply sending this query to the database so it will return results every time irrespective of the login info:
select Username, Password from UserLog
So of course it will pass since you are not filtering the records. As long as you have 1 record in the database, it will pass.
You need to send the user login info and check if a record exists with the login info for the current user that you are trying to authenticate:
IEnumerable users = db
.Query("select Username, Password from UserLog where UserName = #UserName and Password = #Password",
new {UserName = txtUsername.Text, Password = // put the password here});
if (users.Any())
{
// authenticated so do whatever
}

Error happened while connection to oracle via c#

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.

Prevent ODP.net connetion from being open with expired password

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.

Add a new User for the database in mongodb

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.

Categories

Resources