protected override async Task OnProvisioningAsync() { DesignPackage.Install(ClientContext, Site, PackageInfo, PackageUrl); DesignPackage.Apply(ClientContext, Site, PackageInfo); await ClientContext.ExecuteQueryAsync(); }
protected void ActivateSandboxSolution_Click(object sender, EventArgs e) { var spContext = SharePointContextProvider.Current.GetSharePointContext(Context); using (var clientContext = spContext.CreateUserClientContextForSPHost()) { // get the solution gallery var solutionGallery = clientContext.Web.Lists.GetByTitle("Solution Gallery"); clientContext.Load(solutionGallery); clientContext.Load(solutionGallery.RootFolder); clientContext.ExecuteQuery(); // get the DesignPackageInfo (which is the same name for a sandbox solution) var wsp = new DesignPackageInfo() { // during deployment, the solution ID is not necessary PackageGuid = Guid.Empty, // 4c16c0b9-0162-43ad-a8e9-a4b810e58a56 PackageName = "PreventDeleteSites" }; // install the solution from the file url var filerelativeurl = solutionGallery.RootFolder.ServerRelativeUrl + "/PreventDeleteSites.wsp"; DesignPackage.Install(clientContext, clientContext.Site, wsp, filerelativeurl); clientContext.ExecuteQuery(); } }
/// <summary> /// Uploads and installs a sandbox solution package (.WSP) file, replacing existing solution if necessary. /// </summary> /// <param name="site">Site collection to install to</param> /// <param name="packageGuid">ID of the solution, from the solution manifest (required for the remove step)</param> /// <param name="sourceFilePath">Path to the sandbox solution package (.WSP) file</param> /// <param name="majorVersion">Optional major version of the solution, defaults to 1</param> /// <param name="minorVersion">Optional minor version of the solution, defaults to 0</param> public static void InstallSolution(this Site site, Guid packageGuid, string sourceFilePath, int majorVersion = 1, int minorVersion = 0) { string fileName = Path.GetFileName(sourceFilePath); LoggingUtility.Internal.TraceInformation((int)EventId.InstallSolution, CoreResources.WebExtensions_InstallSolution, fileName, site.Context.Url); var rootWeb = site.RootWeb; var sourceFileName = Path.GetFileName(sourceFilePath); var rootFolder = rootWeb.RootFolder; rootWeb.Context.Load(rootFolder, f => f.ServerRelativeUrl); rootWeb.Context.ExecuteQueryRetry(); rootFolder.UploadFile(sourceFileName, sourceFilePath, true); var packageInfo = new DesignPackageInfo() { PackageName = fileName, PackageGuid = packageGuid, MajorVersion = majorVersion, MinorVersion = minorVersion, }; LoggingUtility.Internal.TraceVerbose("Uninstalling package '{0}'", packageInfo.PackageName); DesignPackage.UnInstall(site.Context, site, packageInfo); try { site.Context.ExecuteQueryRetry(); } catch (ServerException ex) { // The execute query fails is the package does not already exist; would be better if we could test beforehand if (ex.Message.Contains("Invalid field name. {33e33eca-7712-4f3d-ab83-6848789fc9b6}")) { LoggingUtility.Internal.TraceVerbose("Package '{0}' does not exist to uninstall, server returned error.", packageInfo.PackageName); } else { throw; } } var packageServerRelativeUrl = UrlUtility.Combine(rootWeb.RootFolder.ServerRelativeUrl, fileName); LoggingUtility.Internal.TraceVerbose("Installing package '{0}'", packageInfo.PackageName); // NOTE: The lines below (in OfficeDev PnP) wipe/clear all items in the composed looks aka design catalog (_catalogs/design, list template 124). // The solution package should be loaded into the solutions catalog (_catalogs/solutions, list template 121). DesignPackage.Install(site.Context, site, packageInfo, packageServerRelativeUrl); site.Context.ExecuteQueryRetry(); // Remove package from rootfolder var uploadedSolutionFile = rootFolder.Files.GetByUrl(fileName); uploadedSolutionFile.DeleteObject(); site.Context.ExecuteQueryRetry(); }
public static void UploadCustomSolution(ClientContext clientContext, string wspPath) { if (null == clientContext) { throw new ArgumentNullException("clientContext"); } if (String.IsNullOrEmpty(wspPath)) { throw new ArgumentNullException("wspPath"); } var wspName = wspPath.Contains("\\") ? wspPath.Substring(wspPath.LastIndexOf("\\", StringComparison.Ordinal) + 1) : wspPath; // Check if the wsp exists already. if (!CustomSolutionExists(clientContext, wspName)) { // Upload the file to the solution gallery. QuerySolutionGallery(clientContext, solutionGallery => { var file = new FileCreationInformation { Content = System.IO.File.ReadAllBytes(wspPath), Url = wspName, Overwrite = true }; solutionGallery.RootFolder.Files.Add(file); clientContext.ExecuteQuery(); }); } // Make sure the solution is activated. var fileRelUrl = ""; QuerySolutionGallery(clientContext, solutionGallery => { clientContext.Load(solutionGallery.RootFolder); clientContext.ExecuteQuery(); fileRelUrl = String.Format("{0}{1}", AppendSlash(solutionGallery.RootFolder.ServerRelativeUrl), wspName); }); var wsp = new DesignPackageInfo { PackageGuid = Guid.Empty, PackageName = wspName.Substring(0, wspName.LastIndexOf(".wsp", StringComparison.OrdinalIgnoreCase)) }; try { clientContext.Load(clientContext.Site); DesignPackage.Install(clientContext, clientContext.Site, wsp, fileRelUrl); clientContext.ExecuteQuery(); } catch (ServerException) { // Likely already activated. } }
/// <summary> /// Activate user solution based on workflow template information /// </summary> /// <param name="wfSolution">Encapsulates workflow solution information - package name is mandatory</param> public void ActivateWorkflowSolution(WorkflowTemplateInfo wfSolution) { // install the solution from the file url var filerelativeurl = templateLibrary.RootFolder.ServerRelativeUrl + "/" + Path.GetFileName(wfSolution.PackageFilePath); DesignPackageInfo packageInfo = new DesignPackageInfo() { PackageGuid = wfSolution.PackageGuid, PackageName = wfSolution.PackageName }; DesignPackage.Install(clientContext, clientContext.Site, packageInfo, filerelativeurl); clientContext.ExecuteQuery(); logger.WriteMessage("Workflow solution " + Path.GetFileName(wfSolution.PackageFilePath) + " is activated."); ActivateWorkflowFeature(wfSolution.FeatureId); }
/// <summary> /// Uploads and installs a sandbox solution package (.WSP) file, replacing existing solution if necessary. /// </summary> /// <param name="site">Site collection to install to</param> /// <param name="packageGuid">ID of the solution, from the solution manifest (required for the remove step)</param> /// <param name="sourceFilePath">Path to the sandbox solution package (.WSP) file</param> /// <param name="majorVersion">Optional major version of the solution, defaults to 1</param> /// <param name="minorVersion">Optional minor version of the solution, defaults to 0</param> public static void InstallSolution(this Site site, Guid packageGuid, string sourceFilePath, int majorVersion = 1, int minorVersion = 0) { string fileName = Path.GetFileName(sourceFilePath); Log.Info(Constants.LOGGING_SOURCE, CoreResources.WebExtensions_InstallSolution, fileName, site.Context.Url); var rootWeb = site.RootWeb; var sourceFileName = Path.GetFileName(sourceFilePath); var rootFolder = rootWeb.RootFolder; rootWeb.Context.Load(rootFolder, f => f.ServerRelativeUrl); rootWeb.Context.ExecuteQueryRetry(); rootFolder.UploadFile(sourceFileName, sourceFilePath, true); var packageInfo = new DesignPackageInfo() { PackageName = fileName, PackageGuid = packageGuid, MajorVersion = majorVersion, MinorVersion = minorVersion, }; Log.Debug(Constants.LOGGING_SOURCE, "Uninstalling package '{0}'", packageInfo.PackageName); DesignPackage.UnInstall(site.Context, site, packageInfo); site.Context.ExecuteQueryRetry(); var packageServerRelativeUrl = UrlUtility.Combine(rootWeb.RootFolder.ServerRelativeUrl, fileName); Log.Debug(Constants.LOGGING_SOURCE, "Installing package '{0}'", packageInfo.PackageName); // NOTE: The lines below (in OfficeDev PnP) wipe/clear all items in the composed looks aka design catalog (_catalogs/design, list template 124). // The solution package should be loaded into the solutions catalog (_catalogs/solutions, list template 121). DesignPackage.Install(site.Context, site, packageInfo, packageServerRelativeUrl); site.Context.ExecuteQueryRetry(); // Remove package from rootfolder var uploadedSolutionFile = rootFolder.Files.GetByUrl(fileName); uploadedSolutionFile.DeleteObject(); site.Context.ExecuteQueryRetry(); }
/// <summary> /// Activates a design package based on package name /// Starting point: http://sharepoint.stackexchange.com/questions/90809/is-it-possible-to-activate-a-solution-using-client-code-in-sharepoint-online-201 /// </summary> /// <param name="context"></param> /// <param name="filePathOrName">The filename of the package</param> /// <param name="siteRelativeUrlToLibrary">Site relative URL to the library of the package</param> public void ActivateDesignPackage(ClientContext context, string filePathOrName, string siteRelativeUrlToLibrary) { // if we pass in a full path, correct this var nameOfPackage = Path.GetFileNameWithoutExtension(filePathOrName); context.Load(context.Site); context.Load(context.Web); context.ExecuteQuery(); var stagedFileUrl = UriUtilities.CombineServerRelativeUri(context.Site.ServerRelativeUrl, siteRelativeUrlToLibrary, nameOfPackage + ".wsp"); var packageInfo = GetPackageInfoWithLatestVersion(context, nameOfPackage, stagedFileUrl); Log.Info("Installing solution package " + GetFileNameFromPackageInfo(packageInfo)); DesignPackage.Install(context, context.Site, packageInfo, stagedFileUrl); context.ExecuteQuery(); DeleteFile(context, stagedFileUrl); }
protected override void ProcessRecord() { base.ProcessRecord(); var ctx = base.Context; ctx.Load(ctx.Site, s => s.ServerRelativeUrl); ctx.ExecuteQuery(); DesignPackageInfo dpi = new DesignPackageInfo(); dpi.PackageGuid = Guid.Empty; dpi.MajorVersion = MajorVersion; dpi.MinorVersion = MinorVersion; dpi.PackageName = Identity; string url = ctx.Site.ServerRelativeUrl.TrimEnd('/') + "/_catalogs/solutions/" + Identity; DesignPackage.Install(ctx, ctx.Site, dpi, url); ctx.ExecuteQuery(); }
private static void UploadWebTemplate(ClientContext cc) { Site newsite = cc.Site; Web newWeb = cc.Web; cc.Load(newsite); cc.Load(newWeb); cc.ExecuteQuery(); List solutionGallery = newWeb.Lists.GetByTitle("Solution Gallery"); cc.Load(solutionGallery); cc.Load(solutionGallery.RootFolder); cc.ExecuteQuery(); string filepath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Contoso Template.wsp"); string filename = Path.GetFileName(filepath); string filerelativeurl = solutionGallery.RootFolder.ServerRelativeUrl + "/" + filename; FileCreationInformation newFile = new FileCreationInformation(); newFile.Content = System.IO.File.ReadAllBytes(filepath); newFile.Overwrite = true; newFile.Url = filename; Microsoft.SharePoint.Client.File uploadedFile = solutionGallery.RootFolder.Files.Add(newFile); cc.Load(uploadedFile); cc.ExecuteQuery(); DesignPackageInfo wsp = new DesignPackageInfo() { PackageGuid = Guid.Empty, PackageName = "Contoso Template" }; DesignPackage.Install(cc, cc.Site, wsp, filerelativeurl); cc.ExecuteQuery(); }
private void DeploySandboxSolution(object modelHost, SiteModelHost siteModelHost, SandboxSolutionDefinition sandboxSolutionDefinition) { var site = siteModelHost.HostSite; var context = site.Context; var existingSolutionFile = FindExistingSolutionFile(siteModelHost, sandboxSolutionDefinition); var existingSolution = FindExistingSolution(siteModelHost, sandboxSolutionDefinition); InvokeOnModelEvent(this, new ModelEventArgs { CurrentModelNode = null, Model = null, EventType = ModelEventType.OnProvisioning, Object = existingSolutionFile, ObjectType = typeof(File), ObjectDefinition = sandboxSolutionDefinition, ModelHost = modelHost }); if (existingSolution != null) { TraceService.Information((int)LogEventId.ModelProvisionProcessingExistingObject, "Processing existing sandbox solution"); var fileItem = existingSolution.ListItemAllFields; context.Load(fileItem); context.ExecuteQueryWithTrace(); var currentFileName = fileItem["FileLeafRef"].ToString(); if (!currentFileName.Contains(sandboxSolutionDefinition.FileName)) { currentFileName = currentFileName.Replace(string.Format("-v{0}.{1}.wsp", 1, 0), string.Empty); } else { currentFileName = sandboxSolutionDefinition.FileName; } var info = new DesignPackageInfo { PackageGuid = sandboxSolutionDefinition.SolutionId, MajorVersion = 1, MinorVersion = 0, PackageName = Path.GetFileNameWithoutExtension(currentFileName) }; // deactivate and remove TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "Deleting existing sandbox solution via DesignPackage.UnInstall()"); DesignPackage.UnInstall(context, site, info); context.ExecuteQueryWithTrace(); } //var solutionGallery = site.RootWeb.Lists.GetByTitle("Site Assets"); //var folder = solutionGallery.RootFolder; var folder = site.RootWeb.RootFolder; context.Load(folder); context.ExecuteQueryWithTrace(); var fileCreatingInfo = new FileCreationInformation { Url = sandboxSolutionDefinition.FileName, Overwrite = true }; if (sandboxSolutionDefinition.Content.Length < 1024 * 1024 * 1.5) { fileCreatingInfo.Content = sandboxSolutionDefinition.Content; } else { fileCreatingInfo.ContentStream = new System.IO.MemoryStream(sandboxSolutionDefinition.Content); } var newFile = folder.Files.Add(fileCreatingInfo); context.Load(newFile); context.Load(newFile, f => f.ServerRelativeUrl); TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "Uploading new sandbox solution to root site folder"); context.ExecuteQueryWithTrace(); if (sandboxSolutionDefinition.Activate) { var info = new DesignPackageInfo { PackageGuid = sandboxSolutionDefinition.SolutionId, MajorVersion = 1, MinorVersion = 0, PackageName = Path.GetFileNameWithoutExtension(sandboxSolutionDefinition.FileName) }; // activate and remove TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "Activating sandbox solution via DesignPackage.Install()"); DesignPackage.Install(context, site, info, newFile.ServerRelativeUrl); context.ExecuteQueryWithTrace(); // clean up the file TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "Deleting sandbox file from root site folder"); newFile.DeleteObject(); context.ExecuteQueryWithTrace(); } InvokeOnModelEvent(this, new ModelEventArgs { CurrentModelNode = null, Model = null, EventType = ModelEventType.OnProvisioned, Object = newFile, ObjectType = typeof(File), ObjectDefinition = sandboxSolutionDefinition, ModelHost = modelHost }); }
private void DeployDesignPackage(object modelHost, SiteModelHost siteModelHost, DesignPackageDefinition definition) { var site = siteModelHost.HostSite; var sandboxSolution = FindExistingSolutionById(siteModelHost, definition.SolutionId); InvokeOnModelEvent(this, new ModelEventArgs { CurrentModelNode = null, Model = null, EventType = ModelEventType.OnProvisioning, Object = sandboxSolution, ObjectType = typeof(SPUserSolution), ObjectDefinition = definition, ModelHost = modelHost }); if (sandboxSolution != null) { TraceService.Information((int)LogEventId.ModelProvisionProcessingExistingObject, "Processing existing design package"); } else { TraceService.Information((int)LogEventId.ModelProvisionProcessingExistingObject, "Processing new design package"); } var designPackageInfo = new DesignPackageInfo(definition.FileName, definition.SolutionId, definition.MajorVersion, definition.MinorVersion); if (definition.Install) { // removing first if (sandboxSolution != null) { TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "Deleting existing sandbox solution"); siteModelHost.HostSite.Solutions.Remove(sandboxSolution); var catalog = siteModelHost.HostSite.RootWeb.GetCatalog(SPListTemplateType.SolutionCatalog); try { var solutionFile = catalog.RootFolder.Files[sandboxSolution.Name]; if (solutionFile.Exists) { solutionFile.Delete(); } } catch { TraceService.Information((int)LogEventId.ModelProvisionProcessingExistingObject, "Error while deleting design package"); } } TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "Deploying design package file to the root folder of the root web"); var rootFolder = site.RootWeb.RootFolder; var tmpDesignPackageFile = rootFolder.Files.Add(definition.FileName, definition.Content, true); TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, string.Format("Installing design package from URL:[{0}]", tmpDesignPackageFile.ServerRelativeUrl)); DesignPackage.Install(site, designPackageInfo, tmpDesignPackageFile.ServerRelativeUrl); sandboxSolution = FindExistingSolutionById(siteModelHost, definition.SolutionId); if (definition.Apply) { TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "Applying design package"); DesignPackage.Apply(site, designPackageInfo); } else { TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "Apply == false. Skipping design package activation"); } // cleanup if (tmpDesignPackageFile.Exists) { tmpDesignPackageFile.Delete(); } InvokeOnModelEvent(this, new ModelEventArgs { CurrentModelNode = null, Model = null, EventType = ModelEventType.OnProvisioned, Object = sandboxSolution, ObjectType = typeof(SPUserSolution), ObjectDefinition = definition, ModelHost = modelHost }); } else { TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "Activate = false. Continue provision"); if (sandboxSolution != null) { TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "Solution is NOT NULL. Checking Apply status"); if (definition.Apply) { TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "Applying design package"); DesignPackage.Apply(site, designPackageInfo); } else { TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "Apply == false. Skipping design package activation"); } } else { TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "Solution is NULL. Skipping Apply status"); } sandboxSolution = FindExistingSolutionById(siteModelHost, definition.SolutionId); InvokeOnModelEvent(this, new ModelEventArgs { CurrentModelNode = null, Model = null, EventType = ModelEventType.OnProvisioned, Object = sandboxSolution, ObjectType = typeof(SPUserSolution), ObjectDefinition = definition, ModelHost = modelHost }); } }
private void DeployArtifact(SiteModelHost modelHost, DesignPackageDefinition definition) { var site = modelHost.HostSite; var context = site.Context; //var existingSolutionFile = FindExistingSolutionFile(siteModelHost, definition); var existingSolution = FindExistingSolutionById(modelHost, definition.SolutionId); InvokeOnModelEvent(this, new ModelEventArgs { CurrentModelNode = null, Model = null, EventType = ModelEventType.OnProvisioning, Object = existingSolution, ObjectType = typeof(File), ObjectDefinition = definition, ModelHost = modelHost }); // uninstalling existing one if (existingSolution != null && definition.Install) { TraceService.Information((int)LogEventId.ModelProvisionProcessingExistingObject, "Processing existing sandbox solution"); var fileItem = existingSolution.ListItemAllFields; context.Load(fileItem); context.ExecuteQueryWithTrace(); var currentFileName = fileItem["FileLeafRef"].ToString(); //if (!currentFileName.Contains(definition.FileName)) // currentFileName = currentFileName.Replace(string.Format("-v{0}.{1}.wsp", 1, 0), string.Empty); //else // currentFileName = definition.FileName; var packageFileName = Path.GetFileNameWithoutExtension(currentFileName); var packageFileNameParts = packageFileName.Split('-'); var packageName = packageFileNameParts[0]; var versionParts = packageFileNameParts[1].Replace("v", string.Empty) .Split('.'); var packageMajorVersion = int.Parse(versionParts[0]); var packageMinorVersion = int.Parse(versionParts[1]); var info = new DesignPackageInfo { PackageGuid = definition.SolutionId, MajorVersion = packageMajorVersion, MinorVersion = packageMinorVersion, PackageName = packageName, }; // cleaning up AppliedDesignGuid at root web to enable 'force' uninstall var rootWeb = site.RootWeb; rootWeb.AllProperties["AppliedDesignGuid"] = null; rootWeb.Update(); context.ExecuteQueryWithTrace(); // deactivate and remove TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "Deleting existing sandbox solution via DesignPackage.UnInstall()"); DesignPackage.UnInstall(context, site, info); try { context.ExecuteQueryWithTrace(); } catch (Exception uninstallException) { // pass this one // bug in SharePoint's DesignPackage.UnInstall method if (!uninstallException.ToString().Contains("33e33eca-7712-4f3d-ab83-6848789fc9b6")) { throw; } } } // installing new if (definition.Install) { var folder = site.RootWeb.RootFolder; context.Load(folder); context.ExecuteQueryWithTrace(); var fileCreatingInfo = new FileCreationInformation { Url = definition.FileName, Overwrite = true }; if (definition.Content.Length < 1024 * 1024 * 1.5) { fileCreatingInfo.Content = definition.Content; } else { fileCreatingInfo.ContentStream = new MemoryStream(definition.Content); } var newFile = folder.Files.Add(fileCreatingInfo); context.Load(newFile); context.Load(newFile, f => f.ServerRelativeUrl); TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "Uploading new sandbox solution to root site folder"); context.ExecuteQueryWithTrace(); var info = new DesignPackageInfo { PackageGuid = definition.SolutionId, MajorVersion = definition.MajorVersion, MinorVersion = definition.MinorVersion, PackageName = Path.GetFileNameWithoutExtension(definition.FileName) }; // activate and remove TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "DesignPackage.Install()"); DesignPackage.Install(context, site, info, newFile.ServerRelativeUrl); context.ExecuteQueryWithTrace(); // clean up the file TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "Deleting sandbox file from root site folder"); newFile.DeleteObject(); context.ExecuteQueryWithTrace(); existingSolution = FindExistingSolutionById(modelHost, definition.SolutionId); } if (definition.Apply) { var info = new DesignPackageInfo { PackageGuid = definition.SolutionId, MajorVersion = definition.MajorVersion, MinorVersion = definition.MinorVersion, PackageName = Path.GetFileNameWithoutExtension(definition.FileName) }; // apply TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "DesignPackage.Apply()"); DesignPackage.Apply(context, site, info); context.ExecuteQueryWithTrace(); } InvokeOnModelEvent(this, new ModelEventArgs { CurrentModelNode = null, Model = null, EventType = ModelEventType.OnProvisioned, Object = existingSolution, ObjectType = typeof(File), ObjectDefinition = definition, ModelHost = modelHost }); }