How to install programmatically an App in SharePoint 2013 preview

Hi,

If you're interesting about the new App development model in SharePoint 2013 Peview, may be you want to install an App programmatically in a SharePoint site.

First, I recommend to read my previous article about How to install an App with PowerShell.

PowerShell is a better installation mode than C#, so I recommend to use this method first if you want to install an app automatically. But in some cases, you could want to install an App programmatically with .Net code (for example in C#). For example, if you want to create a web part to create automatically a sub web and install an App on this new site.

In fact, deploy an App programmatically is very simple, thanks to the new SPWeb.LoadAndInstallApp method on the SPWeb class. 

With this new method, you can directly import and install a new app on a specific SharePoint 2013 site :

 

 string webUrl = "https://sharepoint2013site/";
string appFullPath = "c:\\mysampleapp.app";
Guid appId = Guid.Empty;

using (site = new SPSite(webUrl))
{
    using (web = site.OpenWeb())
    {
        Stream package = null;
        try
        {
            package = File.OpenRead(appFullPath);
            SPAppInstance appInstance = web.LoadAndInstallApp(package);
            if (appInstance != null && appInstance.Status == SPAppInstanceStatus.Initialized)
            {
                //Your App is installed now
                appId = appInstance.Id; 
            }
        }
        finally
        {
            if (package != null)
                package.Close();
        }
    }
}

An important thing to know is that after this method, the app instance is still in "deployement". It means that the app is not finished to install, you must wait and check the status if you want to wait the complete deployment.

For example:

 

 SPAppInstance localInstance = null;
int maxTry = 150;
int count = 0;
do
{
    Thread.Sleep(1000);
    localInstance = web.GetAppInstanceById(appId);
    count++;
}
while (localInstance != null && localInstance.Status != SPAppInstanceStatus.Installed && count < maxTry);

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

You can download a command line simple sample bellow.

CustomAppInstaller.zip