i am using ODBC to pull data from active directory to get the email for a particular username using the code below.
how can i use AD to pull all the usernames of peolel who report into a prticular manager?
i can transverse the org chart in outlook so im thinking i can do the same using AD...
ideas?
System.Data.OleDb.OleDbConnection con;
System.Data.OleDb.OleDbCommand cmd;
con = new System.Data.OleDb.OleDbConnection("Provider=ADsDSOObject;dsn=Active Directory Provider");
con.Open();
//Create a command object on this connection
string strSQL = "SELECT mail FROM 'LDAP://DC=amrs,DC=win,DC=ml,dc=COM' WHERE samaccountname = '" + UserName.Replace(#"AMRS\", "") + "'";
cmd = new System.Data.OleDb.OleDbCommand(strSQL, con);
try
{
return Convert.ToString ( cmd.ExecuteScalar() );
}
catch (System.Data.OleDb.OleDbException exc)
{
return "ERROR: " + exc.ToString();
}
finally
{
con.Close();
}
See if the manager attribute in AD is set? It should return you the distinguished name of the manager. You can then parse the string to figure out the samAccountName of the manager.
Then just repeat your search using the manager's distinguished name.
Now if the manager attribute isn't set....
Maybe search by department code, and then check the title of everyone in the department?
Might want to look into the Directory Services class.
This link gives you a basic tutorial on how to query AD
Related
I am trying to redirect my login.htm to index.htm in c#. both files are inside the folder named 'default'. after logging in, if the credential is correct, I want to redirect the login page to index. using the code below, but there is an exception message Attempted to cancel thread.. Is there a way to fix this?? How you can help me. Thanks in advance.
[WebMethod]
public void LogMeIn(string user, string pass) {
try {
using (MySqlConnection dbConn = new MySqlConnection(connectionString())) {
if (dbConn.State == System.Data.ConnectionState.Open) dbConn.Close();
dbConn.Open();
MySqlCommand sqlCmd = new MySqlCommand("SELECT * FROM tbllogin WHERE userName = '" + user + "' AND passWord ='" + pass + "'", dbConn);
int rowCount = (int)sqlCmd.ExecuteScalar();
if (rowCount > 0) {
HttpContext.Current.Response.Redirect("../default/index.htm"); //redirect to new htm page
}
}
}
catch (Exception ex) {
Console.WriteLine("Error Message : " + ex.Message);
}
}
HttpContext.Current.Response.Redirect(HttpContext.Current.Request.ApplicationPath+"default/index.htm");
Or you can use this way.
HttpContext.Current.Response.Redirect is trying to send users to the wrong place
HttpContext.Current.Response.Redirect("~/default/index.htm");
There are some errors and unnecesary code in your code example:
There is no need to check if dbConn is already opened, because it was just created
The SELECT * caused an Exception when doing later an ExecuteScalar because the table has more than one column. You should change it to SELECT COUNT(*)
Because how Microsoft handles how the flow of the page is done, if you don't end the response when doing the Response.Redirect you may need to catch an ThreadAbortException. To end the response you could check Redirect(string url, bool endResponse) overload
That being said, you should do use parametrized queries, because unexpected or malicious input could cause you problems.
I create a free host in 000webhost. It is active, here is link http://rndsctvlab.hostei.com/.
Then I create database have information
$mysql_host = "mysql10.000webhost.com";
$mysql_database = "a9127803_data1";
$mysql_user = "<username>";
$mysql_password = "<password>";
Now I want to connect and add data to mysql on this host from my pc. I write a code in C# but it fail,
It warning
Here is my code
string myConnection = "Server=31.170.160.97;Database=a9127803_data1; Port=3306;User ID=<username>;Password=<password>";
conDatabase = new MySqlConnection(myConnection);
string Query = "INSERT into ex1 (ID,Name,Address) values ('" + txt_ID.Text + "','" + txt_name.Text + "','" + txt_address.Text + "');";
MySqlCommand cmdDataBase = new MySqlCommand(Query, conDatabase);
MySqlDataReader myReader;
try
{
conDatabase.Open();
myReader = cmdDataBase.ExecuteReader();
MessageBox.Show("SAVE");
while (myReader.Read())
{
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
How can I fix it? Thank you for help.
I've had this problem before and found that I needed to allow user permissions from IP addresses on MySQL 5 databases.
So for example, if you use MySQL Workbench or MySQL Query Broswer, the query would be like this to allow all hosts:
GRANT ALL ON a9127803_data1.* TO 'a9127803_data2'#'YourIpAddress';
Not quite sure how 000webhost works, or if you can do queries from there, but the above MySQL query is what helped me. You can customise it for each database and user.
EDIT:
Should you need to customise the permissions, look at this MySQL link for more examples using the GRANT syntax
EDIT 2:
If you need to grant permissions via command line, here is an example:
cd C:\mysql //push to your MySQL directory on your server
.\bin\mysql -u user -p
//Enter Password now
grant all on YourDb.YourDbTable to YourUser#YourIpAddress;
Once you enter this, it should grant the permissions for your user on the IP address of your choosing, for the database and table selected.
Firstly please don't mark it as duplicate I know it's been asked multiple times here but none of the links helped me.
I am trying to access database which is located on shared drive, also both the mdb file and the folder in which it is stored have full access to everyone. I have hosted my application on two different machines.
Below is the code to connect to access DB
OleDbDataAdapter dataAdapter = null;
DataTable dtAttendance = new DataTable();
try
{
string conStr = System.Configuration.ConfigurationManager.ConnectionStrings["AccessDBPath"].ToString();
using (OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Mode= Share Deny None;Data Source= " + conStr))
{
conn.Open();
OleDbCommand cmd = new OleDbCommand(#"Select EmployeeId AS UserId,AttendanceDate , format(Int(Duration/60),'0') AS Duration,format(Duration Mod 60,'0') AS Remain FROM AttendanceLogs
where EmployeeId =" + userid.ToString() + " and Year(AttendanceDate)="+year+" and Month(AttendanceDate)="+month+" order by AttendanceDate desc", conn);
dataAdapter = new OleDbDataAdapter();
dataAdapter.SelectCommand = cmd;
dataAdapter.Fill(dtAttendance);
conn.Close();
}
}
catch(Exception ee)
{}
Only first time when I tested it, it worked properly and thereafter it started throwing above error.
I am new to web development and .NET too. I have a website written in ASP.NET using C#. How should I display full name of the current user instead of username using sessions? Please help me. Here is the code.
Code behind login page:-
Session["username"] = txt_un.Text.Trim().ToString();
Code behind userprofile page:-
string str = "select fullname from userprofile where username=#username";
Label4.Text = Session["username"].ToString();
The problem is that fullname is not present on the login page. It is present in userprofile page. How to display fullname on the userprofile page after user click on login button?User is using his registration_id as username. But I don't want to display registration_id,I want to display fullname of the user.Pls give me answer in detail. Thank you in advance.
You need to get first name, Whenever you login in your app with this select query and ExecuteScalar.
string str = "select fullname from userprofile where username=#username";
Then You need to store the first name into a session
Session[firstName]=Query return value
And finally you can give
if(Session[firstName]!=null)
{
Label4.Text=Session[firstName].ToString()
}
I really don't understand clearly what you need but somehow you need user's full name to show some where using username,
Here one simple function that will return you the full name.
I assume you know how to connect your webpage to the SQL Server and all the functions
public string GetFullName(string username)
{
string query = "select fullname from userprofile where username ='" + staffID + "'";
SqlConnection conn = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(query, conn);
conn.Open();
SqlDataReader reader = cmd.ExecuteReader();
try
{
while (reader.Read())
{
return reader["fullname"].ToString();
}
}
catch (Exception ex)
{
HttpContext.Current.Session["Error_Message_Session"] = ex;
HttpContext.Current.Response.Redirect("Error.aspx", false);
}
finally
{
conn.Close();
}
return "-";
}
The function that i used here is from my own project, this is how i get the full name by his username, similarly i had the same problem so i did this, just a simple static function
I'm just a beginner in C#. I'm using XAMPP server for MySQL database and Visual C# 2010. Then I have created a database named "testdb" in phpMyAdmin and a table named "login". I have inserted my username and password in the table. I'm doing a simple WinForm login where I made two text boxes for username and password and a button. I have my codes done and there's no compiler error. But I had troubled in one line. It says "Unable to connect to any of the specified MySQL hosts". I added MySql.Data to my references. I want to fetch the data in the database table when I'm going to log in. Then authorize the user or if not matched, it will prompt an error message.
Here is my code:
using MySql.Data.MySqlClient;
public bool Login(string username, string password)
{
MySqlConnection con = new MySqlConnection("host=localhost;username…");
MySqlCommand cmd = new MySqlCommand("SELECT * FROM login WHERE username='" +
username + "' AND password='" + password + "';");
cmd.Connection = con;
con.Open(); // This is the line producing the error.
MySqlDataReader reader = cmd.ExecuteReader();
if (reader.Read() != false)
{
if (reader.IsDBNull(0) == true)
{
cmd.Connection.Close();
reader.Dispose();
cmd.Dispose();
return false;
}
else
{
cmd.Connection.Close();
reader.Dispose();
cmd.Dispose();
return true;
}
}
else
{
return false;
}
}
*I hope for your your feedback. :)
Your immediate problem is probably either an incorrect connection string or the database server is not available. The connection string should be something like this
Server=localhost;Database=testdb;Uid=<username>;Pwd=<password>;
with <username> and <password> replaced with your actual values.
Besides that your code has several issues and you should definitely look into them if this is intended to become production code and probably even if this is just a toy project to learn something. The list is in particular order and may not be comprehensive.
Do not hard code your connection string. Instead move it to a configuration file.
Do not include plain text passwords in configuration files or source code. There are various solutions like windows authentication, certificates or passwords protected by the Windows Data Protection API.
Do not just dispose IDisposable instances by calling IDisposable.Dispose(). Instead use the using statement to release resources even in the case of exceptions.
Do not build SQL statements using string manipulation techniques. Instead use SqlParameter to prevent SQL injection attacks.
Do not store plain text passwords in a database. Instead at least store salted hashes of the passwords and use a slow hash function, not MD5 or a member of the SHA family.
You can use IDbCommand.ExecuteScalar to retrieve a scalar result and avoid using a data reader.
Comparing a boolean value with true or false is redundant and just adds noise to your code. Instead of if (reader.IsDBNull(0) == true) you can just use if (reader.IsDBNull(0)). The same holds for if (reader.Read() != false) what is equivalent to if (reader.Read() == true) and therefore also if (reader.Read()).
Using an O/R mapper like the Entity Framework is usually preferred over interacting with the database on the level of SQL commands.
Try modifying your ConnectionString accordingly to the Standard MySQL ConnectionString:
Server=myServerAddress;Database=myDataBase;Uid=myUsername;Pwd=myPassword;
Source:
MySQL ConnectionStrings
You can also take a look at the following link, that shows how to connect to a MySQL database using C#:
Creating a Connector/Net Connection String (MYSQL)
Make it simple and sql injection free, and also don't forget to add MySql.Web
in your references since your using XAMPP
public bool Login(string username, string password)
{
DataTable dt = new DataTable();
string config = "server=....";
using (var con = new MySqlConnection { ConnectionString = config })
{
using (var command = new MySqlCommand { Connection = con })
{
con.Open();
command.CommandText = #"SELECT * FROM login WHERE username=#username AND password=#password";
command.Parameters.AddWithValue("#username", username);
command.Parameters.AddWithValue("#password", password);
dt.Load(command.ExecuteReader());
if (dt.Rows.Count > 0)
return true;
else
return false;
} // Close and Dispose command
} // Close and Dispose connection
}