How to create SQL Server Login programmatically?

Ramy Mahrous 0 Tallied Votes 419 Views Share

Here's I wrote some code to create login on SQL Server.
1- Add references (Microsoft.SqlServer.Smo, Microsoft.SqlServer.SqlEnum and Microsoft.SqlServer.ConnectionInfo) to your project.
2- Call method CreateLogin which takes to some arguments (documented)

//This code developed by Ramy Mahrous 
//ramyamahrous@hotmail.com
//Its contents is provided "as is", without warranty.
//Add reference to Microsoft.SqlServer.Smo,  Microsoft.SqlServer.SqlEnum and Microsoft.SqlServer.ConnectionInfo

/// <summary>
/// Creates login on SQL Server.
/// </summary>
/// <param name="username">Username if login type is windows please provide the domian name</param>
/// <param name="password">Username's password</param>
/// <param name="defaultDatabase">User's default database</param>
/// <param name="loginType">Type of login</param>
public void CreateDatabase(string username, string password, 
string defaultDatabase, LoginType loginType)
{
Server sqlServerInstance = new Server(
new Microsoft.SqlServer.Management.Common.ServerConnection(
new System.Data.SqlClient.SqlConnection("Data Source=.;Initial Catalog=Master;Integrated Security=True")));// your connection string I place mine for illustration.. DON'T HARDLY WRITE IT, pass it as argument or add it in application configuration.
Login loginObj = new Login(sqlServerInstance, username);
loginObj.DefaultDatabase = defaultDatabase;
loginObj.LoginType = loginType;
loginObj.Enable();
loginObj.Create(password); //set the password
//there're many properties to do some tasks related to Login object...
}
serkan sendur 821 Postaholic Banned

this must be effect of "essentials" featured coder badge :D

Ramy Mahrous 401 Postaholic Featured Poster

loooooooooooooooooooooooool, we must proof there are unknown soldiers in C# community ;)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.