So, for a few days i've been trying to do this, still, i've passed trough a few problems but im stuck on this one. looks like my connection to AD is working fine (after alot of digging and googling)
i have this.
I'm not a developer, still i have studied c# in school and i have some knowledge of it, still, i need to make this work in order to save time when it comes the time to create a new user.
private void btn_create_Click(object sender, EventArgs e)
{
bool valid = false;
PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "PTLISDC04", "Users");
{
valid = ctx.ValidateCredentials("myadminaccount", "mypassword");
}
UserPrincipal usr = new UserPrincipal(ctx);
usr.UserPrincipalName = tb_user.Text.ToString() + "#kpmg.com";
usr.Name = tb_lname.Text.ToString() + ", " + lb_fname.Text.ToString() + " " + lbl_mname.Text.ToString();
usr.Description = tb_empid.Text.ToString();
usr.EmailAddress = tb_email.Text.ToString();
usr.DisplayName = tb_lname.Text.ToString() + ", " + lb_fname.Text.ToString() + " " + lbl_mname.Text.ToString();
usr.Save();
usr.Dispose();
ctx.Dispose();
MessageBox.Show("User Created!");
and when i press the "create user" button i get this:
An unhandled exception of type
'System.DirectoryServices.AccountManagement.PrincipalOperationException'
occurred in System.DirectoryServices.AccountManagement.dll
Additional information: An invalid dn syntax has been specified.
and it points to this line on code
usr.UserPrincipalName = tb_user.Text.ToString() + "#kpmg.com";
if i comment this line it goes to the next and so on
Related
I keep getting this exception over and over. I've tried separating my query into two separate queries, that didn't work. I've checked to make sure the db connection is closed elsewhere before it's opened during this method, it's definitely closed before the function is called and opened before any queries.
Below iss the code for the function. I've set breakpoints and the query itself is fine. The code is the exact same that I used previously for updating a PIN function, with just the query string changed, so I don't know why it's causing issues:
Code:
public void transferMoney(string senderIban, decimal senderBalance, string receiverIban, decimal transferAmount,string messageOptional)
{
//myBankAccount.AccountPin = updatedPin;
DataTable dtUser = new DataTable();
sqlconnConnection.Open();
string strQuery2 = #"UPDATE Accounts SET Balance = Balance + " + Convert.ToDecimal(transferAmount) + " WHERE GUID = '" + receiverIban + "';"
+ "UPDATE Accounts SET Balance = Balance - " + Convert.ToDecimal(transferAmount) + " WHERE GUID = '" + senderIban + "';";
// example of a Paramaterised SQL statement.
SQLiteCommand sqlcomCommand2 = new SQLiteCommand(strQuery2, sqlconnConnection);
SQLiteDataAdapter sqldatadptAdapter = new SQLiteDataAdapter(sqlcomCommand2); // local SQL data Adaptor
try
{
// sqldatadptAdapter.Fill(dtUser);
sqlcomCommand2.ExecuteNonQuery();
}
catch (Exception ex)
{
// Exception will the "thrown" when there was a problem
throw new Exception($"UPDATE WAS unsuccessful:\n{ex.Message}");
}
finally
{
sqlconnConnection.Close();
}
Maybe you have a DB browser opened? Or you have accessed the DB some other way. This error only occurs when DB is modified or used elsewhere. If you can't find it, I'd suggest restarting PC just in case there something hidden :)
P.S. Posting this as answer as I cannot comment under the question for technical reasons :)
This question already has answers here:
Faster way to find out if a user exists on a system?
(4 answers)
Closed 4 years ago.
I am creating db users via a web application like so:
try
{
SetConnection(server);
string sql =
"USE [master]" +
" CREATE LOGIN" + " [TP1\\" + user + "] FROM WINDOWS WITH DEFAULT_DATABASE=[master], " +
"DEFAULT_LANGUAGE=[us_english] " +
"EXEC sys.sp_addsrvrolemember #loginame = N'TP1\\" + user + "', #rolename = N'sysadmin'";
_tableContext.Database.ExecuteSqlCommand(TransactionalBehavior.DoNotEnsureTransaction, sql);
}
catch (Exception e)
{
// log error
throw e;
}
and it works fine.
I was testing the application and typed in a name that does not exist in WINDOWS-NT and got the followiing error:
Windows NT user or group 'TP1\MyName' not found. Check the name
again.\r\n'TP1\MyName' is not a valid login or you do not have
permission.\r\nChanged database context to 'master
After some time researching I found that I can SELECT * FROM sysusers
BUT this only shows me if a user is already registered on that server.
I would like to know if there is a way for me to check if the username is a valid NT-user?
This question will be marked as a duplicate but for the purpose of being clear I just wanted to share my specific scenario:
I found the answer here thanks to #SteveDrake.
My implementation :
using (PrincipalContext pc = new PrincipalContext(ContextType.Domain))
{
user = "MyName";
UserPrincipal up = UserPrincipal.FindByIdentity(
pc,
IdentityType.SamAccountName,
user);
bool UserExists = (up != null);
}
NOTE I changed the ContextType to Domain
When i try this one, can't access the default file in login. I already checked the the database and tables they are the same. I'm trying to create multiple users but I can't login. What is the proper way of accessing multiple user?
if (Sessions.Current.authenticated != null)
{
if (Sessions.Current.authenticated)
{
Response.Redirect("Admin/Default2.aspx");
}
}
}
protected void login(object sender, EventArgs e)
{
string username = txtUsername.Text.ToString();
string password = txtPassword.Text.ToString();
DataTable dtUser = DBConnector.getTable("SELECT * FROM User WHERE Username = '" + username + "' AND Password = '" + password, false);
if (dtUser.Rows.Count > 0)
{
DataRow dr = dtUser.Rows[0];
Sessions.Current.authenticated = true;
Sessions.Current.lastfirst = dr["Name"].ToString();
Sessions.Current.Usertype = dr["userType"].ToString();
Response.Redirect("Admin/Default2.aspx");
Response.Redirect("web/Default.aspx");
}
}
Ok first of all this code is atrocious. Anybody can use SQL injection to login to your website without using a password or username. Use parameterized queries instead.
Dont make queries in this way
DataTable dtUser = DBConnector.getTable("SELECT * FROM User WHERE Username = '" + username + "' AND Password = '" + password, false);
Now to the problem you are facing. i.e you are not hitting the Default page. This is because of
Response.Redirect("Admin/Default2.aspx");
Once this code is executed the control leaves this page and goes to Page_Load event of Default.aspx2. So doesnt matter what you write after that, its not gonna get executed.
I'm having a really strange problem with an application I wrote a while back. It has worked without issues, but after leaving it alone for a while, it simply stopped functioning. I'll attach the code here:
try
{
using (Process proc = Process.Start(starter))
{
windowHider();
proc.WaitForExit();
DateTime endStamp = DateTime.Now;
endStamp = truncate(endStamp);
TimeSpan diff = endStamp.Subtract(startStamp);
string programSource = "applicationName";
string logLocation = "Application";
string occurance = "Var='" + varName + "' Var2='"+ var2Name + "' Var3='" + var3Name + "' Var4='" + var4Name + "' Var5='" + var5Name + "' Var6='" + var6Name + "'";
try
{
if (!EventLog.SourceExists(programSource))
{
EventLog.CreateEventSource(programSource, logLocation);
}
else
{
EventLog.WriteEntry(programSource, occurance);
}
}
catch (Exception err)
{
string message = "There was an error with usage logging. Please contact IT.";
MessageBox.Show(message);
errorLogger(message, err.ToString(), ((Control)sender).Name);
this.Close();
}
this.Close();
}
}
When the process that was started exits, the program writes to the application log. For some reason, however, I am getting the following error:
Exception: System.ComponentModel.Win32Exception (0x80004005): The
specified path is invalid
It cites this line as the cause:
EventLog.WriteEntry(programSource, occurance);
Any ideas as to what this sudden problem could be?
I figured it out! There was something corrupted in the registry, and there must have been another corrupted component lurking around somewhere. I changed the sourcename, and it worked without any issues.
The original sourcename works on other machines, which makes me think it was definitely just something wonky with the registry.
I'm trying to write simple application in C# which will allow me to backup, zip and send over ftp my SQL Server database.
One problem I have encountered is that I'm not able to create the backup file (.bak) if I try to do it in different location than "C:\Program Files\Microsoft SQL Server\MSSQL.3\MSSQL\Backup" or "C:\Program Files\Microsoft SQL Server\MSSQL.3\MSSQL\Data" folder. I understand that this is a premission problem. Could someone point me to the resources or write here a short snippet how to programmatically add such a permission to any folder on my system.
Regards
Kris
i assume you are running your programm as a scheduled task ... did you give writing permissions to the target folder for the executing user of the task??
edit:
with permissions you can have 2 scenarios:
windows authenification
mixed authentification
if you are using windows authentification, the read and write permissions of the windows user are taken. otherwise the permissions for the sql server service account.
and this behaviour makes sense to me and maybe hits the nail in your scenario!
edit 2:
i don't want to encourage you to do so ... some admins may hate you when you mess up their acl's
but this may do the trick
btw: Magnus Johansson already gave you a "try-this" link
no matter for which method you go - be sure to hand in the correct user (as descriped above!)
(for full history)
...
side-note:
i know this is not the exact answer to your question, but i would recommend you smo to generate backups ...
like
using Microsoft.SqlServer.Management.Smo;
var bdi = new BackupDeviceItem(/* your path inlcuding desired file */);
var backup = new Backup
{
Database = /* name of the database */,
Initialize = true
};
backup.Devices.Add(bdi);
var server = new Server(this.SqlServer);
try
{
backup.SqlBackup(server);
}
catch (Exception ex)
{
// * log or sth
}
you only have to care for the .dll's. take assemblies for the desired server version (some params/properties vary through different server versions)
more info here
Ok Guys, Magnus and dittodhole! Thanks a lot for your help. I have combined Magnus'es link to the article on setting up permisions on the folder together with some more research and finally I've got it :).
So reassuming, I'm using Smo, and to create a folder with proper permissions I have to look for the group instead of win32_Users. Here you go a short snippet if someone finds this post he can find it usefull:
string tempPath = Directory.CreateDirectory("C:\\path_to_your_folder").FullName;
//set permissions
SelectQuery sQuery = new SelectQuery("Win32_Group",
"Domain='" +
System.Environment.UserDomainName.ToString() +
"'");
try
{
DirectoryInfo myDirectoryInfo = new DirectoryInfo("C:\\path_to_your_folder");
DirectorySecurity myDirectorySecurity = myDirectoryInfo.GetAccessControl();
ManagementObjectSearcher mSearcher = new ManagementObjectSearcher(sQuery);
foreach (ManagementObject mObject in mSearcher.Get())
{
string User = System.Environment.UserDomainName + "\\" + mObject["Name"];
if(User.StartsWith("your-machine-name\\SQL"))
{
myDirectorySecurity.
AddAccessRule(new FileSystemAccessRule(User,
FileSystemRights.FullControl,
AccessControlType.Allow));
}
}
myDirectoryInfo.SetAccessControl(myDirectorySecurity);
}
catch (Exception ex)
{
Console.WriteLine(ex.StackTrace);
}
Again thanks everyone for your help! Stackoverflow rocks!
Here is a procedure is use for back up in C#.Hope it helps
public void BackupDatabase (string BackUpLocation, string BackUpFileName, string
DatabaseName, string ServerName )
{
DatabaseName = "[" + DatabaseName + "]";
string fileUNQ = DateTime.Now.Day.ToString() + "_" + DateTime.Now.Month.ToString() + "_" + DateTime.Now.Year.ToString() +"_"+ DateTime.Now.Hour.ToString()+ DateTime.Now .Minute .ToString () + "_" + DateTime .Now .Second .ToString () ;
BackUpFileName = BackUpFileName + fileUNQ + ".bak";
string SQLBackUp = #"BACKUP DATABASE " + DatabaseName + " TO DISK = N'" + BackUpLocation + #"\" + BackUpFileName + #"'";
string svr = "Server=" + ServerName + ";Database=master;Integrated Security=True";
SqlConnection cnBk = new SqlConnection(svr);
SqlCommand cmdBkUp = new SqlCommand(SQLBackUp, cnBk);
try
{
cnBk.Open();
cmdBkUp.ExecuteNonQuery();
Label1.Text = "Done";
Label2.Text = SQLBackUp + " ######## Server name " + ServerName + " Database " + DatabaseName + " successfully backed up to " + BackUpLocation + #"\" + BackUpFileName + "\n Back Up Date : " + DateTime.Now.ToString();
}
catch (Exception ex)
{
Label1.Text = ex.ToString();
Label2.Text = SQLBackUp + " ######## Server name " + ServerName + " Database " + DatabaseName + " successfully backed up to " + BackUpLocation + #"\" + BackUpFileName + "\n Back Up Date : " + DateTime.Now.ToString();
}
finally
{
if (cnBk.State == ConnectionState.Open)
{
cnBk .Close();
}
}
}
Take a look at this article.
Remember to set the permissions for the account that the SQL Server instance is running with.
Although this may not answer your immediate question, I'd advice you to look into SQL Server Integration Services (SSIS). This looks like the exact thing SSIS was created for, and in the 2008 version there's the possibility to use C# code if needed, should the standard components not do what you need (earlier versions used VB.NET).
MSDN SSIS Info Link 1
SSIS 2005 Tutorial Link 2
Take a look at it.