使用CSOM安装Sharepoint App

时间:2014-08-12 09:01:27

标签: sharepoint-2013 csom sharepoint-apps

是否有人知道是否可以使用CSOM在sharepoint网站上自动安装特定应用程序?我们有在sharepoint上创建新站点的机制,我们需要的是使用CSOM自动化在每个新创建的站点上安装特定Sharepoint App的过程。

有人可以提供代码示例或一些有用的链接吗?

1 个答案:

答案 0 :(得分:3)

SharePoint CSOM API Web class公开以下方法:

如何通过CSOM部署(上传和安装)SharePoint App

/// <summary>
/// Deploy SP App 
/// </summary>
/// <param name="context">Client context</param>
/// <param name="appFullPath">Full path to app file (.app)</param>
/// <returns></returns>
private static AppInstance DeployApp(ClientContext context, string appFullPath)
{
    using (var packageStream = System.IO.File.OpenRead(appFullPath))
    {
       var appInstance = context.Web.LoadAndInstallApp(packageStream);
       context.Load(appInstance);
       context.ExecuteQuery();
       return appInstance;
    }
 }

用法

以下示例演示了如何将SP App部署到SharePoint Online

using (var ctx = new ClientContext(url))
{              
      ctx.Credentials = new SharePointOnlineCredentials(userName, securePassword);
      var appInstance = DeployApp(ctx, @"C:\Packages\SPApp.app");
      if (appInstance != null && appInstance.Status == AppInstanceStatus.Initialized)
      {
          Console.WriteLine("App was installed.");
      }
 }

<强>更新

上述解决方案旨在将应用安装到developer site

以下解决方案演示了如何将应用安装到non developer site

public class SPAppManager
{
    /// <summary>
    /// Deploy SP App 
    /// </summary>
    /// <param name="context">Client context</param>
    /// <param name="appFullPath">Full path to app file (.app)</param>
    /// <returns></returns>
    public static AppInstance Deploy(ClientContext context, string appFullPath)
    {
        EnsureDeveloperFeature(context);
        using (var packageStream = System.IO.File.OpenRead(appFullPath))
        {
            var appInstance = context.Web.LoadAndInstallApp(packageStream);
            context.Load(appInstance);
            context.ExecuteQuery();
            return appInstance;
        }
    }


    /// <summary>
    /// Ensure Developer Feature 
    /// </summary>
    /// <param name="ctx"></param>
    private static void EnsureDeveloperFeature(ClientContext ctx)
    {
        var result = ctx.LoadQuery(ctx.Site.Features.Where(f => f.DefinitionId == DeveloperFeatureId));
        ctx.ExecuteQuery();
        if (result.Any()) return;
        var feature = ctx.Site.Features.Add(DeveloperFeatureId,true, FeatureDefinitionScope.None);
        ctx.ExecuteQuery();
    }


    private static readonly Guid DeveloperFeatureId = new Guid("e374875e-06b6-11e0-b0fa-57f5dfd72085");
} 

Gist: SPAppManager.cs

用法

 using (var ctx = GetContext(webUri,userName,password))
 {
     var appInstance = SPAppManager.Deploy(ctx, @"C:\Packages\SPApp.app");
     if (appInstance != null && appInstance.Status == AppInstanceStatus.Initialized)
     {
        Console.WriteLine("App was installed.");
     }
 }