共用方式為


Automating add-in/app installation to SharePoint sites using CSOM

How do I install apps/add-ins from store, app catalog or directly to the site? ” is relatively common question cross partners and customers. We are getting this question or request quite often at the Office 365 Developer Patterns and Practices (PnP) Yammer group or through other forums. Frank Marasco from the Office Dev PnP core team blogged about this already while back with title of “SideLoading Guideance” (Finglish is contagious), but due the amount of questions, thought that it would be worth while to have another blog post on the same topic.

Before heading to the actual meat of the post, let’s have a short look on the different options of the getting your add-in/app deployed, so that we understand the different options and requirements around the request.

Add-in/app scoping

There is two different ways for add-in/app to exist in the SharePoint or to be visible in the sites and it’s important to understand the difference so that we can decide the right deployment mechanism for add-in/apps.

Web scoped add-ins/apps

This is more typical model where add-in/app is located directly in the context of specific site. Add-in/app is installed directly to the site and is visible in the site contents view. Web scoped add-ins/apps can install app parts, app custom actions and app installed events are firing for provider hosted add-in when they are added to the site. Following drawing explains the model in practice.

image

  1. End users are adding add-ins/apps to SharePoint sites
  2. App is created or instantiated directly to the site and it can have optional app/add-in web, which is created directly under the specific site. Add-in/app webs are basically just sub sites in the site collections with specific template. App-in/app installed events are fired in the  case of the provider hosted add-ins/apps and optional app parts, including optional custom actions, are being visible in the host web where the add-in/app was installed
  3. User accesses the add-in from the site contents or from add-in/app part
  4. Content is rendered from the add-in/app. Could come from provider hosted environment or from the add-in/app web

 

Tenant scoped add-ins/apps

This is capability also know as “app stapling” where you install add-in to app catalog site collection and then use “Deployment” mechanism to push the add-in/app available for other sites. Add-in/app is only installed once to the app catalog site collection and in other sites there will be just links pointing to this centralized instance under app catalog. This means that custom actions and app parts are being deployed only to app catalog and not to the other sites where the app is being visible. Also app install, uninstall and upgrade events are only executed on the app catalog site context, since that’s the actual location where the app is being installed.

Richard diZerega has great blog post on this few years back called SharePoint 2013 app deployment through “app stapling”.

 image

  1. Add-ins/apps are being installed by app catalog owner
  2. Add-in/app is being installed on the app catalog. Possible app events, app parts, custom actions are being visible in the app catalog site after the initial creation of the app. This is the only location where the app actually is being installed
  3. Users access the add-in/app from their browsers at the normal sites
  4. Add-ins/apps have been pushed to the normal sites with the “Deployment” mechanism, which makes them visible in the site contents view, but does not really install the add-in/app to the sites

 

How to automate web scoped add-in/app installation?

Coming back on the actual topic of the post. Since you cannot use tenant scoped deployment model to get add-in parts or custom actions to be visible in the sites, it’s relatively common ask to get web scoped add-ins/apps deployed to sites for example as part of the initial site provisioning. This is actually possible, but has few limitations, due security challenges and store processes. We cannot achieve this for add-ins/apps in the store, but we can actually make this work within enterprise development scenarios, where you have control of the add-ins/apps which are being installed. 

Pre-requisites

There are few different pre-requisites for making add-ins/apps being installed directly to the sites using web scoped approach. Here’s a short list of the pre-requisites.

  • Add-in/app which being installed has to request tenant level permissions, which is the reason why this is not suitable model for store add-ins/apps
  • Add-in/app which being installed has to be instantiated or specifically trusted by the tenant administrator once before it can be pushed to sites
  • Add-in/app which being installed has to be pushed by uploading app file directly to the site where it’s being added
    • You cannot push add-ins/apps from the store or from the app catalog to the sites
  • When you install add-in/app to the site, you will need to enable so called site loading feature
    • Regardless of the statement in the blog post at Office Apps MSDN blog, this is fully supported. It’s not specifically recommended due the fact that then you do not have centralized control on the add-in/app, but it’s also the only way to achieve certain business scenarios.

 

How does it work in practice?

Let’s have a look on the process and code in practice with the following video. This shows quickly the app-stapling process and also what are the steps getting add-ins/apps installed on any SharePoint using CSOM, with app part and custom action support. To be able to install add-in/apps directly to the site using CSOM, you’ll need to perform following steps

  • Install add-in/app once on the tenant level to grant the needed permissions for the add-in/app
  • Connect to SharePoint site
  • Enabled side loading feature at site collection level
  • Install add-in/app using Web.LoadAndInstallApp method
  • Deactivate side loading feature at site collection level

You can also find this video from the Office 365 Developer Patterns and Practices video blog at Channel 9.

CSOM code to install and app/add-in to SharePoint site

Here’s the full code of the console application, which is used to connect to SharePoint online and install add-in/app to the site.

 // Unique ID for side loading feature
 Guid sideloadingFeature = new Guid("AE3A1339-61F5-4f8f-81A7-ABD2DA956A7D");
 // Prompt for URL
 string url = GetUserInput("Please provide URL for the site where app is being installed: \n");
 // Prompt for Credentials 
 Console.WriteLine("Enter Credentials for {0}", url);
 string userName = GetUserInput("SharePoint username: ");
 SecureString pwd = GetPassword();
  
 // Get path to the location of the app file in file system
 string path = GetUserInput("Please provide full path to your app package: \n");
  
 // Create context for SharePoint online
 ClientContext ctx = new ClientContext(url);
 ctx.AuthenticationMode = ClientAuthenticationMode.Default;
 ctx.Credentials = new SharePointOnlineCredentials(userName, pwd);
  
 // Get variables for the operations
 Site site = ctx.Site;
 Web web = ctx.Web;
  
 try
 {
     // Make sure we have side loading enabled. 
     // Using PnP Nuget package extensions.
     site.ActivateFeature(sideloadingFeature);
     try
     {
         // Load .app file and install that to site
         var appstream = System.IO.File.OpenRead(path);
         AppInstance app = web.LoadAndInstallApp(appstream);
         ctx.Load(app);
         ctx.ExecuteQuery();
     }
     catch
     {
         throw;
     }
     // Disable side loading feature using 
     // PnP Nuget package extensions. 
     site.DeactivateFeature(sideloadingFeature);
 }
 catch (Exception ex)
 {
     Console.ForegroundColor = ConsoleColor.Red;
     Console.WriteLine(string.Format("Exception!"), ex.ToString());
     Console.WriteLine("Press any key to continue.");
     Console.Read();
 }

 

Q&A

Can I automate app/add-in installation for apps in the SharePoint store?

No. This is not possible, since store apps have licensing implications, so they cannot be just installed using simple API calls.

Can I automate app/add-in installation from app-catalog

Slightly depends on the exact objective. You can push add-ins/apps from the catalog using “app-stapling” model, but that has limitation around app parts, custom actions and app installation events. With app-stapling you create instance of the add-in/app to the app catalog site collection and then push links to specific sites. You cannot deploy isolated instances of the add-in/app to different sites and site collections. You can only achieve this with the code and process explained in this blog post.

Can I use app-one/add-in only token to install app on the site using this code?

No. This does not work, since app-only means that you are basically running in the system context and SharePoint cannot associate app/add-in to the right person in the app service application. Code will execute, but installation will fail in the UI in the end like with following picture.

image

Video shows deployment of provider hosted add-in/app to SharePoint sites, but would same process work with SP hosted add-in?

No. Model where you actually create own app instances to specific sites with LoadAndInstallApp() does only work for provider hosted add-ins/apps. App stapling from app catalog works for SP hosted add-ins and provider hosted add-ins.

Add-in/app has to request tenant level permissions, so it can only then be used by tenant administrator?

No. Trust operation has to be done by tenant administrator, but actual API calls in the add-in/app do not require that high permissions. Add-in/app could for example perform read or write operations to host web, which would only require that level of permission from the end user using the app/add-in. Alternatively add-in/app which has been installed, could use app-only permissions which basically means same as classic elevation of privileges in server side code.

Is there any other way to make this work?

Yes. You could always fall back on so called http post pattern, but that’s not also recommended approach since that means that you’d mimic browser operations for the “Trust” operation by mimicking the needed http post traffic. This does work, but if there’s any changes in the UI of the targeted operation, your code could get broken. We do not intentially do UI changes which would break these, but we cannot also guarantee that changes which would impact your code would not be done.

 

Office 365 Developer Patterns and Practices

Office365PnPLogoRed_thumb1Techniques showed in this blog post are part of the Core.SideLoading sample in the Office 365 Developer Patterns and Practices guidance, which contains more than 100 samples and solutions demonstrating different patterns and practices related on the app model development together with additional documentation related on the app model techniques.

Check the details around PnP from dev.office.com at https://aka.ms/OfficeDevPnP. Please join us on sharing patterns and practices for the community for the benefit of the community. If you have any questions, comments or feedback related on this sample, blog post or anything on PnP, please use the Office 365 Developer Patterns and Practices Yammer group at https://aka.ms/OfficeDevPnPYammer.

“Sharing is caring”

Comments

  • Anonymous
    December 17, 2015
    Thanks for sharing Vesa, One more question, Do we have any way to add programmatically our SharePoint Add-in Part (as a WebPart) to our sites when we are provisioning? I mean, It is good to have automatic way to install it, but could be amazing to have automatic way to add it to our pages too. (and automatically do the Trust verification on behalf the user). Regards!

  • Anonymous
    March 14, 2016
    Hi Vesa, clear post! Could you add the why to your explanation: why is it currently so hard to add an add-in from the add-in catalog to a site programmatically? Why are some scenarios excluded: we want to add SharePoint hosted add-ins to sites during a remote provisioning process.

  • Anonymous
    October 27, 2016
    Thanks for the detailed post to automate the process.It is very helpful to the beginners to work on automating the deployment process.But i have the small doubt.Can we deploy the app to the entire site collection level instead of specific site using CSOM.Regards,Anil

  • Anonymous
    November 01, 2016
    Hi Vesa,Thanks for the article, one note App stapling "deployment link"doesn't exist in the new look and feel i need to switch to classic mode to see it, where to submit this for change?

  • Anonymous
    January 13, 2017
    The comment has been removed

  • Anonymous
    February 16, 2017
    Купить цветы в Краснодаре реально недорого, и при этом получить бесплатно консультацию профессионального флориста. Возможно ли это? Мы говорим - да! Спешите сделать приятное своим близким - родным и любимым, друзьям и коллегам, детям и родителям. Доброе и приятное - долго хранится в памяти, накладывая отпечаток на взаимоотношения между людьми. А ведь сегодня это так просто! Заказываем доставку букета нежных роз, шашлык и напитки, оригинальный подарок - и половина дела сделана. Останется только добавить к этому личное участие - очное или по телефону...

  • Anonymous
    March 26, 2017
    Hi Vesa,Excellent post!I know a lot of time has passed since this post was written, but I was brought here because I tried to use this approach to automate the installation of a SharePoint Framework add-in (.sppkg).Although, whenever I try to install the app I get the following error:"Client Side Solutions cannot be used in this location."Any specific reason why we can't use this approach with these type of solutions? Anything that I can be doing wrong? Thanks,Rodrigo

    • Anonymous
      July 20, 2017
      Also having this problem. Is there any workaround in place for this?
  • Anonymous
    May 16, 2017
    Hello, just wanted to tekl you, I loved this blog post.It was practical. Keep on posting!