Create web application in share point server farm using C# code

Code snippet below is to solve this problem. It uses reflection to use Microsoft.SharePoint.Administration.SPWebApplicationProvisioningJobDefinition internal class to create provision job and create web application in share point server farm. To see the exact use of code snippet, i have also created one sample application.

Description
Code snippet below is to solve this problem. It uses reflection to use Microsoft.SharePoint.Administration.SPWebApplicationProvisioningJobDefinition internal class to create provision job and create web application in share point server farm. To see the exact use of code snippet, i have also created one sample application.

Problem this article addresses
Creating web application in single server environment using share point API works very straight forward. But when used in share point server farm same _newApplication.Provision() dont work as expected. During my R & D i found blogs on the net to install hotfix to resolve the problem and use _newApplication.ProvisionGlobally() api to provision the web application in the server farm. This again did not work as expected.

Code Snippet
public class SiteCreation
    {

        private SPWebApplication _newApplication;
        private SPWebApplicationBuilder _webAppBuilder;

        /// <summary>
        /// Provisoing servers to the farm
        /// </summary>
        /// <param name="application">Web application instance</param>
        private void ProvisionGlobally(SPWebApplication application)
        {
            SPWebServiceInstance localContent = SPWebServiceInstance.LocalContent;
            if (application is SPAdministrationWebApplication)
            {
                localContent = SPWebServiceInstance.LocalAdministration;
            }
            while ((localContent != null) && ((localContent.Status == SPObjectStatus.Provisioning) || (localContent.Status == SPObjectStatus.Online)))
            {
                application.Provision();//first provision locally
                break;
            }
            if (SPFarm.Local.TimerService.Instances.Count > 1)
            {
                ProvisionTimerJob(application, true);//now provisiong globally
            }
        }


        /// <summary>
        /// Create a job to provision site to servers in farm
        /// </summary>
        /// <param name="application">Application name</param>
        /// <param name="resetIis">Flag to reset IIS after provisioning</param>
        private void ProvisionTimerJob(SPWebApplication application, bool resetIis)
        {
            // SPWebApplicationProvisioningJobDefinition is an internal class so we need to use reflection to set it. 305:  
            // SPWebApplicationProvisioningJobDefinition definition = new SPWebApplicationProvisioningJobDefinition(application, resetIis);
            Type SPWebApplicationProvisioningJobDefinition =
                Type.GetType(
                "Microsoft.SharePoint.Administration.SPWebApplicationProvisioningJobDefinition, Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c");
            ConstructorInfo SPWebApplicationProvisioningJobDefinitionConstructor =
                SPWebApplicationProvisioningJobDefinition.GetConstructor(
                BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.InvokeMethod | BindingFlags.Public,
                null,
                new Type[] { typeof(SPWebApplication), typeof(bool) }, null);
            object jobDef =
                SPWebApplicationProvisioningJobDefinitionConstructor.Invoke(new object[] { application, resetIis });
            // jobDef.Schedule = new SPOneTimeSchedule(DateTime.Now);
            PropertyInfo scheduleProp = SPWebApplicationProvisioningJobDefinition.GetProperty("Schedule",
                BindingFlags.FlattenHierarchy |
                BindingFlags.NonPublic |
                BindingFlags.Instance |
                BindingFlags.InvokeMethod |
                BindingFlags.GetProperty |
                BindingFlags.Public);
            scheduleProp.SetValue(jobDef, new SPOneTimeSchedule(DateTime.Now), null);
            // jobDef.Update();
            MethodInfo update = SPWebApplicationProvisioningJobDefinition.GetMethod("Update", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.InvokeMethod | BindingFlags.FlattenHierarchy, null, new Type[] { }, null);
            update.Invoke(jobDef, new object[] { });
        }
        /// <summary>
        /// create site usgin webapplicatoin builder
        /// </summary>
        /// <param name="_siteURL"></param>
        /// <param name="_siteName"></param>
        /// <param name="_ownerLogin"></param>
        /// <param name="_ownerName"></param>
        /// <returns></returns>
        public bool CreateSite(string _siteURL,string _siteName,string _ownerLogin,string _ownerName,string portno,string ApplicationPool,string database)
        {
            //change the port number
            int _portNumber = Convert.ToInt32(portno);
            try
            {
                
                _webAppBuilder = new SPWebApplicationBuilder(SPFarm.Local);
                        
              
                _webAppBuilder.Port = _portNumber;

                _webAppBuilder.ApplicationPoolId = ApplicationPool;
                _webAppBuilder.ApplicationPoolUsername = _ownerLogin;


                System.Security.SecureString password = new System.Security.SecureString();

                string passWord = ""; //change the password

                char[] pass = passWord.ToCharArray();
                foreach (char c in pass)
                    password.AppendChar(c);

                _webAppBuilder.ApplicationPoolPassword = password;

                _webAppBuilder.CreateNewDatabase = true; // Create new database            

                _webAppBuilder.DatabaseName = database;    // database name            

              
                _webAppBuilder.UseNTLMExclusively = true;  // Use NTLM authentication

                _newApplication = _webAppBuilder.Create(); // Create new web application
                _newApplication.ApplicationPool.CurrentIdentityType = IdentityType.SpecificUser;
                _newApplication.ApplicationPool.Username =_ownerLogin;
                _newApplication.ApplicationPool.Password = passWord;

                //To provision the web application in single server environmnet use _newApplication.Provision()

                //Provision the web application in share point server farm
                ProvisionGlobally(_newApplication);
                //Update the changes in web server farm
                _newApplication.Update();
                SPSite mySiteCollection = _newApplication.Sites.Add(_newApplication.GetResponseUri(SPUrlZone.Default).ToString(),                       //Root
                    "TCS Demo",              // site title
                     "TCS Demo",             //description
                    1033,                         //language
                    "STS#1",              //Blank site template  
                    _ownerLogin, // Site owner
                     _ownerName,                 // Name
                    "test@test.com"); //Email
                SPSite _siteCollection = new SPSite(_newApplication.GetResponseUri(SPUrlZone.Default).ToString());
                _siteCollection.AllWebs.Add(_siteName, "Testing", "Test site created", 1033, "STS#1", false, false);
            }
            catch (Exception ex)
            {
                
                throw;
                
            }
            
            return true;
        }
     }

By Devil Scorpio   Popularity  (1858 Views)