FCI-Helwan blog

Just another FCI-H weblog

How to create SQL Server Login programmatically?

Q. How to create SQL Server Login programmatically?

I got this question from Daniweb C# forum, and of course when I need to do something against SQL Server object from .net I go to SMO (SQL Server Management Objects) which provides a great functionalities to do anything with SQL Server instead of going on SSMS and create some scripts then embedding them into stored procedure then call it…. off…
Anyway to avoid showing how much I’m talkative…

Create any C# project type (Windows, Class Library or even Console one), add reference to Microsoft.SqlServer.Smo, Microsoft.SqlServer.ConnectionInfo
and Microsoft.SqlServer.SqlEnum
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..
Login loginObj = new Login(sqlServerInstance, @"DomainName\UserName");
loginObj.DefaultDatabase = "Master";
loginObj.LoginType = LoginType.WindowsUser;
loginObj.Enable();
loginObj.Create("password");
//set the password
//there're many properties to do some tasks related to Login object...

If you used LoginType.WindowsUser, be sure to provide valid windows username and if you aren’t on Domain use the machine name instead.

If you need to create SQL login use LoginType.SqlLogin…

You can explore Login class more on http://msdn.microsoft.com/en-us/library/microsoft.sqlserver.management.smo.login.create.aspx

 

 

 

Advertisements

April 28, 2009 - Posted by | .NET Q and A, C#, Microsoft, SMO, SQL Server

3 Comments »

  1. بسم الله

    Comment by Shady Mostafa | May 1, 2009 | Reply

  2. By the way, you don’t need to provide a connection object, empty constructor will go with windows auth and default server

    Comment by Mohamed Meshref | May 5, 2009 | Reply

  3. Thanks, Meshref 🙂

    Comment by Ramy Mahrous | May 5, 2009 | Reply


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: