Search This Blog

Saturday, December 24, 2016

How to install an App in SharePoint 2013 programmatically using c#

The below method is used to install the app in the sharepoint site programmatically using C#

InstallAppPart("http://sharepoint2013/site/","d:\\SampleApp\TestApp.app")

public void InstallAppPart(string WebURL, string AppFullPath)
{
   Guid appId = Guid.Empty;

    using(site = new SPSite(WebURL))
   {
       using(web = site.OpenWeb())
       {
            Stream package = null;
            try
           {
              //This code is used to start installing the app
              package = File.OpenRead(AppFullPath);
              SPAppInstance appInstance = web.LoadAndInstallApp(package);
              if (appInstance != null && appInstance.Status == SPAppInstanceStatus.Initialized)
             {
                //Your App is started installing now
                 appId = appInstance.Id;
             }
 
           //This code is used to check the app completeley installed in the sharepoint site
          SPAppInstance newAppInstance = null;
          int maxTry = 150;
          int count = 0;
          do
          {
              Thread.Sleep(1000);
              newAppInstance = web.GetAppInstanceById(appId);
              count++;
          }
          while (newAppInstance != null && newAppInstance.Status != SPAppInstanceStatus.Installed             && count  < maxTry);

         if(newAppInstance != null && newAppInstance .Status == SPAppInstanceStatus.Installed)
         {
                  Console.WriteLine("App installation complete. App URL:" +                localInstance.AppWebFullUrl.ToString());
         }
     }
     finally
     {
        if (package != null)
           package.Close();
     }
   }
 }
}

No comments:

Post a Comment