Ejemplo n.º 1
0
        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();
            }
        }
Ejemplo n.º 2
0
        private void DeployArtifact(SiteModelHandler modelHost, DesignPackageDefinition definition)
        {
            // TODO, implementation
            // Add DesignPackage provision support #166
            // https://github.com/SubPointSolutions/spmeta2/issues/166

            DesignPackageInfo currentArtifact = null;

            InvokeOnModelEvent(this, new ModelEventArgs
            {
                CurrentModelNode = null,
                Model            = null,
                EventType        = ModelEventType.OnProvisioning,
                Object           = currentArtifact,
                ObjectType       = typeof(DesignPackageInfo),
                ObjectDefinition = definition,
                ModelHost        = modelHost
            });

            // TODO

            InvokeOnModelEvent(this, new ModelEventArgs
            {
                CurrentModelNode = null,
                Model            = null,
                EventType        = ModelEventType.OnProvisioned,
                Object           = currentArtifact,
                ObjectType       = typeof(DesignPackageInfo),
                ObjectDefinition = definition,
                ModelHost        = modelHost
            });
        }
Ejemplo n.º 3
0
        /// <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();
        }
Ejemplo n.º 4
0
        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.
            }
        }
 public void ActivateSolution(string solutionName)
 {
     var packageName = solutionName.EndsWith(".wsp") ? solutionName.Substring(0, solutionName.Length - 4) : solutionName;
     var wspPackage = new DesignPackageInfo()
     {
         PackageGuid = Guid.Empty,
         PackageName = packageName,
     };
     InstallSolution(wspPackage, solutionName);
 }
Ejemplo n.º 6
0
        protected override async Task InitializeAsync()
        {
            await base.InitializeAsync();

            PackageUrl = await HarshUrl.EnsureServerRelative(CatalogFolder.Value, DesignPackageName);
            PackageInfo = new DesignPackageInfo()
            {
                PackageName = DesignPackageName,
            };
        }
Ejemplo n.º 7
0
        protected override async Task InitializeAsync()
        {
            await base.InitializeAsync();

            PackageUrl = await HarshUrl.EnsureServerRelative(CatalogFolder.Value, DesignPackageName);

            PackageInfo = new DesignPackageInfo()
            {
                PackageName = DesignPackageName,
            };
        }
Ejemplo n.º 8
0
        public override void DeployModel(object modelHost, DefinitionBase model)
        {
            var siteModelHost = modelHost.WithAssertAndCast <SiteModelHost>("modelHost", value => value.RequireNotNull());
            var definition    = model.WithAssertAndCast <DesignPackageDefinition>("model", value => value.RequireNotNull());

            // TODO

            DesignPackageInfo spObject = null;

            var assert = ServiceFactory.AssertService
                         .NewAssert(definition, spObject)
                         .ShouldNotBeNull(spObject);
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Uninstalls a sandbox solution package (.WSP) file
        /// </summary>
        /// <param name="site">Site collection to install to</param>
        /// <param name="packageGuid">ID of the solution, from the solution manifest</param>
        /// <param name="fileName">filename of the WSP file to uninstall</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 UninstallSolution(this Site site, Guid packageGuid, string fileName, int majorVersion = 1, int minorVersion = 0)
        {
            LoggingUtility.Internal.TraceInformation((int)EventId.UninstallSolution, CoreResources.WebExtensions_UninstallSolution, packageGuid);

            var rootWeb         = site.RootWeb;
            var solutionGallery = rootWeb.GetCatalog((int)ListTemplateType.SolutionCatalog);

            var camlQuery = new CamlQuery();

            camlQuery.ViewXml = string.Format(
                @"<View>  
                        <Query> 
                           <Where><Eq><FieldRef Name='SolutionId' /><Value Type='Guid'>{0}</Value></Eq></Where> 
                        </Query> 
                         <ViewFields><FieldRef Name='ID' /><FieldRef Name='FileLeafRef' /></ViewFields> 
                  </View>", packageGuid);

            var solutions = solutionGallery.GetItems(camlQuery);

            site.Context.Load(solutions);
            site.Context.ExecuteQueryRetry();

            if (solutions.AreItemsAvailable)
            {
                var packageItem = solutions.FirstOrDefault();
                var packageInfo = new DesignPackageInfo()
                {
                    PackageGuid  = packageGuid,
                    PackageName  = fileName,
                    MajorVersion = majorVersion,
                    MinorVersion = minorVersion
                };

                DesignPackage.UnInstall(site.Context, site, packageInfo);
                try
                {
                    site.Context.ExecuteQueryRetry();
                }
                catch (ServerException ex)
                {
                    if (ex.Message.StartsWith("Invalid field name. {33e33eca-7712-4f3d-ab83-6848789fc9b6}", StringComparison.OrdinalIgnoreCase))
                    {
                        LoggingUtility.Internal.TraceVerbose("Package '{0}' does not exist to uninstall, server returned error.", packageInfo.PackageName);
                    }
                }
            }
        }
        /// <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);
        }
Ejemplo n.º 11
0
        /// <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();
        }
        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();
        }
Ejemplo n.º 13
0
        /// <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>
        /// Deactivate user solution based on workflow template information
        /// </summary>
        /// <param name="wfSolution">Encapsulates workflow solution information - package guid is mandatory</param>
        public void DeactivateWorkflowSolution(WorkflowTemplateInfo wfSolution)
        {
            if (wfSolution.PackageGuid.Equals(Guid.Empty))
            {
                throw new Exception("PackageGuid is not specified, please fill in.");
            }
            // uninstall the solution

            DesignPackageInfo packageInfo = new DesignPackageInfo()
            {
                PackageGuid = wfSolution.PackageGuid,
                PackageName = wfSolution.PackageName
            };

            DesignPackage.UnInstall(clientContext, clientContext.Site, packageInfo);

            clientContext.ExecuteQuery();

            logger.WriteMessage("Workflow solution " + wfSolution.PackageName + " is deactivated.");
        }
        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();
        }
Ejemplo n.º 16
0
        protected void DeactivateSandboxSolution_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();

                var wsp = new DesignPackageInfo()
                {
                    // the package guid is necessary to explicitly
                    PackageGuid = new Guid("4c16c0b9-0162-43ad-a8e9-a4b810e58a56"),
                    PackageName = "PreventDeleteSites"
                };

                // uninstall the solution
                DesignPackage.UnInstall(clientContext, clientContext.Site, wsp);
                clientContext.ExecuteQuery();
            }
        }
Ejemplo n.º 17
0
        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();
        }
Ejemplo n.º 18
0
        /// <summary>
        /// Uninstalls a sandbox solution package (.WSP) file
        /// </summary>
        /// <param name="site">Site collection to install to</param>
        /// <param name="packageGuid">ID of the solution, from the solution manifest</param>
        /// <param name="fileName">filename of the WSP file to uninstall</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 UninstallSolution(this Site site, Guid packageGuid, string fileName, int majorVersion = 1, int minorVersion = 0)
        {
            Log.Info(Constants.LOGGING_SOURCE, CoreResources.WebExtensions_UninstallSolution, packageGuid);

            var rootWeb         = site.RootWeb;
            var solutionGallery = rootWeb.GetCatalog((int)ListTemplateType.SolutionCatalog);

            var camlQuery = new CamlQuery();

            camlQuery.ViewXml = string.Format(
                @"<View>  
                        <Query> 
                           <Where><Eq><FieldRef Name='SolutionId' /><Value Type='Guid'>{0}</Value></Eq></Where> 
                        </Query> 
                         <ViewFields><FieldRef Name='ID' /><FieldRef Name='FileLeafRef' /></ViewFields> 
                  </View>", packageGuid);

            var solutions = solutionGallery.GetItems(camlQuery);

            site.Context.Load(solutions);
            site.Context.ExecuteQueryRetry();

            if (solutions.AreItemsAvailable)
            {
                var packageItem = solutions.FirstOrDefault();
                var packageInfo = new DesignPackageInfo()
                {
                    PackageGuid  = packageGuid,
                    PackageName  = fileName,
                    MajorVersion = majorVersion,
                    MinorVersion = minorVersion
                };

                DesignPackage.UnInstall(site.Context, site, packageInfo);
                site.Context.ExecuteQueryRetry();
            }
        }
Ejemplo n.º 19
0
        /// <summary>
        /// Uninstalls a sandbox solution package (.WSP) file
        /// </summary>
        /// <param name="site">Site collection to install to</param>
        /// <param name="packageGuid">ID of the solution, from the solution manifest</param>
        /// <param name="fileName">filename of the WSP file to uninstall</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 UninstallSolution(this Site site, Guid packageGuid, string fileName, int majorVersion = 1, int minorVersion = 0)
        {
            LoggingUtility.Internal.TraceInformation((int)EventId.UninstallSolution, CoreResources.WebExtensions_UninstallSolution, packageGuid);

            var rootWeb = site.RootWeb;
            var solutionGallery = rootWeb.GetCatalog((int)ListTemplateType.SolutionCatalog);

            var camlQuery = new CamlQuery();
            camlQuery.ViewXml = string.Format(
              @"<View>  
                        <Query> 
                           <Where><Eq><FieldRef Name='SolutionId' /><Value Type='Guid'>{0}</Value></Eq></Where> 
                        </Query> 
                         <ViewFields><FieldRef Name='ID' /><FieldRef Name='FileLeafRef' /></ViewFields> 
                  </View>", packageGuid);

            var solutions = solutionGallery.GetItems(camlQuery);
            site.Context.Load(solutions);
            site.Context.ExecuteQuery();

            if (solutions.AreItemsAvailable)
            {
                var packageItem = solutions.FirstOrDefault();
                var packageInfo = new DesignPackageInfo()
                {
                    PackageGuid = packageGuid,
                    PackageName = fileName,
                    MajorVersion = majorVersion,
                    MinorVersion = minorVersion
                };

                DesignPackage.UnInstall(site.Context, site, packageInfo);
                try
                {
                    site.Context.ExecuteQuery();
                }
                catch (ServerException ex)
                {
                    if (ex.Message.StartsWith("Invalid field name. {33e33eca-7712-4f3d-ab83-6848789fc9b6}", StringComparison.OrdinalIgnoreCase))
                    {
                        LoggingUtility.Internal.TraceVerbose("Package '{0}' does not exist to uninstall, server returned error.", packageInfo.PackageName);
                    }
                }
            }
        }
Ejemplo n.º 20
0
        /// <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 solutionGallery = rootWeb.GetCatalog((int)ListTemplateType.SolutionCatalog);
            var sourceFileName = Path.GetFileName(sourceFilePath);
            rootWeb.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.ExecuteQuery();
            }
            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.StartsWith("Invalid field name. {33e33eca-7712-4f3d-ab83-6848789fc9b6}", StringComparison.OrdinalIgnoreCase))
                {
                    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.ExecuteQuery();

            // Remove package from rootfolder
            var uploadedSolutionFile = rootWeb.RootFolder.Files.GetByUrl(fileName);
            uploadedSolutionFile.DeleteObject();
            site.Context.ExecuteQuery();
        }
Ejemplo n.º 21
0
        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
            });
        }
        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
            });
        }
Ejemplo n.º 23
0
        /// <summary>
        /// Deactivate user solution based on workflow template information
        /// </summary>
        /// <param name="wfSolution">Encapsulates workflow solution information - package guid is mandatory</param>
        public void DeactivateWorkflowSolution(WorkflowTemplateInfo wfSolution)
        {
            if (wfSolution.PackageGuid.Equals(Guid.Empty))
            {
                throw new Exception("PackageGuid is not specified, please fill in.");
            }
            // uninstall the solution

            DesignPackageInfo packageInfo = new DesignPackageInfo()
            {
                PackageGuid = wfSolution.PackageGuid,
                PackageName = wfSolution.PackageName
            };

            DesignPackage.UnInstall(clientContext, clientContext.Site, packageInfo);

            clientContext.ExecuteQuery();

            logger.WriteMessage("Workflow solution " + wfSolution.PackageName + " is deactivated.");
        }
Ejemplo n.º 24
0
        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();
            }
        }
Ejemplo n.º 25
0
        protected void DeactivateSandboxSolution_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();

                var wsp = new DesignPackageInfo() {
                    // the package guid is necessary to explicitly 
                    PackageGuid = new Guid("4c16c0b9-0162-43ad-a8e9-a4b810e58a56"),
                    PackageName = "PreventDeleteSites"
                };

                // uninstall the solution
                DesignPackage.UnInstall(clientContext, clientContext.Site, wsp);
                clientContext.ExecuteQuery();
            }
        }
Ejemplo n.º 26
0
        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 InstallSolution(DesignPackageInfo wspInfo, string solutionName)
 {
     var packageName = solutionName.EndsWith(".wsp") ? solutionName : solutionName + ".wsp";
     try
     {
         var solutionFolder = masterPageGallery.RootFolder;
         ctx.Load(solutionFolder);
         var fileUrl = solutionFolder.ServerRelativeUrl + "/" + packageName;
         DesignPackage.Install(ctx, ctx.Site, wspInfo, fileUrl);
         ctx.ExecuteQuery();
     }
     catch(Exception ex)
     {
         Console.WriteLine("{0} install failed", packageName);
         Console.WriteLine("{0}\r\n{1}", ex.Message, ex.StackTrace);
     }
 }
Ejemplo n.º 28
0
 /// <summary>
 /// This is how SharePoint creates the name of the package that is installed
 /// </summary>
 /// <param name="packageInfo"></param>
 /// <returns></returns>
 private static string GetFileNameFromPackageInfo(DesignPackageInfo packageInfo)
 {
     return(string.Format("{0}-v{1}.{2}.wsp", packageInfo.PackageName, packageInfo.MajorVersion, packageInfo.MinorVersion));
 }
Ejemplo n.º 29
0
        /// <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, "Installing sandbox solution '{0}' to '{1}'.", fileName, site.Context.Url);

            var rootWeb = site.RootWeb;
            var solutionGallery = rootWeb.GetCatalog((int)ListTemplateType.SolutionCatalog);
            rootWeb.UploadDocumentToFolder(sourceFilePath, solutionGallery.RootFolder);

            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.ExecuteQuery();
            }
            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.StartsWith("Invalid field name. {33e33eca-7712-4f3d-ab83-6848789fc9b6}", StringComparison.OrdinalIgnoreCase))
                {
                    LoggingUtility.Internal.TraceVerbose("Package '{0}' does not exist to uninstall, server returned error.", packageInfo.PackageName);
                }
                else
                {
                    throw;
                }
            }

            var packageServerRelativeUrl = UrlUtility.Combine(solutionGallery.RootFolder.ServerRelativeUrl, fileName);
            LoggingUtility.Internal.TraceVerbose("Installing package '{0}'", packageInfo.PackageName);
            DesignPackage.Install(site.Context, site, packageInfo, packageServerRelativeUrl);
            //Console.WriteLine("Applying package '{0}'", packageInfo.PackageName);
            //DesignPackage.Apply(siteContext, siteContext.Site, packageInfo);
            site.Context.ExecuteQuery();
        }
Ejemplo n.º 30
0
        /// <summary>
        /// Uninstalls a sandbox solution package (.WSP) file
        /// </summary>
        /// <param name="site">Site collection to install to</param>
        /// <param name="packageGuid">ID of the solution, from the solution manifest</param>
        /// <param name="fileName">filename of the WSP file to uninstall</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 UninstallSolution(this Site site, Guid packageGuid, string fileName, int majorVersion = 1, int minorVersion = 0)
        {
            Log.Info(Constants.LOGGING_SOURCE, CoreResources.WebExtensions_UninstallSolution, packageGuid);

            var rootWeb = site.RootWeb;
            var solutionGallery = rootWeb.GetCatalog((int)ListTemplateType.SolutionCatalog);

            var camlQuery = new CamlQuery();
            camlQuery.ViewXml = string.Format(
              @"<View>
                        <Query>
                           <Where><Eq><FieldRef Name='SolutionId' /><Value Type='Guid'>{0}</Value></Eq></Where>
                        </Query>
                         <ViewFields><FieldRef Name='ID' /><FieldRef Name='FileLeafRef' /></ViewFields>
                  </View>", packageGuid);

            var solutions = solutionGallery.GetItems(camlQuery);
            site.Context.Load(solutions);
            site.Context.ExecuteQueryRetry();

            if (solutions.AreItemsAvailable && solutions.Count > 0)
            {
                var packageItem = solutions.FirstOrDefault();
                var packageInfo = new DesignPackageInfo()
                {
                    PackageGuid = packageGuid,
                    PackageName = fileName,
                    MajorVersion = majorVersion,
                    MinorVersion = minorVersion
                };

                Publishing.DesignPackage.UnInstall(site.Context, site, packageInfo);
                site.Context.ExecuteQueryRetry();
            }
        }
Ejemplo n.º 31
0
        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);
            UninstallSolution(site, packageGuid, fileName, majorVersion, minorVersion);
            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).

            Publishing.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();
        }
Ejemplo n.º 32
0
        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
                });
            }
        }
Ejemplo n.º 33
0
        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
            });
        }
Ejemplo n.º 34
0
 /// <summary>
 /// This is how SharePoint creates the name of the package that is installed
 /// </summary>
 /// <param name="packageInfo"></param>
 /// <returns></returns>
 private static string GetFileNameFromPackageInfo(DesignPackageInfo packageInfo)
 {
     return string.Format("{0}-v{1}.{2}.wsp", packageInfo.PackageName, packageInfo.MajorVersion, packageInfo.MinorVersion);
 }