Wednesday, November 19, 2008

How to create Sharepoint Web Application Programmatically?

Sometimes we want to create Sharepoint web application programmatically (I needed it while I was writing an installer).

The following code will help you in this regard.

public static void Create()
        {
            SPWebApplication newApplication = null;
            int port = 2020;
            string userName = "xdev\\mujtaba";
            string userPass = "p@ssw0rd2";

            SPWebApplicationBuilder appBuilder = new SPWebApplicationBuilder(SPFarm.Local);
            int myPort = Convert.ToInt16(port.ToString());
            appBuilder.Port = myPort;
            appBuilder.ApplicationPoolId = "My Application - " + port.ToString(); //Used to show in the sharepoint application list.
            appBuilder.ApplicationPoolUsername = userName;
            System.Security.SecureString password = new System.Security.SecureString();
            char[] pass = userPass.ToCharArray();
            foreach (char c in pass)
                password.AppendChar(c);
            appBuilder.ApplicationPoolPassword = password;
            appBuilder.CreateNewDatabase = true; // Create new database           
            appBuilder.DatabaseName = "wss_site" + port.ToString() + "_content";    // database name
            //webAppBuilder.DatabaseServer = webAppBuilder.DefaultZoneUri.Host;  //Host name/computer name          
            appBuilder.UseNTLMExclusively = true;  // Use NTLM authentication
            appBuilder.ServerComment = "My Application - " + port.ToString();

            newApplication = appBuilder.Create(); // Create new web application
            newApplication.Name = "My Application - " + port.ToString();


            newApplication.Provision();           //Provision it into web farm

            Console.WriteLine("Application Successfully created.");
        }

You will have to add reference to Microsoft.Sharepoint.dll to you project.
Enjoy it.

1 comment:

  1. Getting error "Value cannot be null." at this line"SPWebApplicationBuilder appBuilder = new SPWebApplicationBuilder(SPFarm.Local);"

    ReplyDelete