protected FeatureCollection LoadWebFeatures(WebModelHost webModelHost)
        {
            var web = webModelHost.HostWeb;
            var context = web.Context;

            context.Load(web, w => w.Features);
            context.ExecuteQuery();

            return web.Features;
        }
        protected WebNavigationSettings GetWebNavigationSettings(WebModelHost webModelHost, WebNavigationSettingsDefinition navigationModel)
        {
            var web = webModelHost.HostWeb;

            var context = web.Context;
            var thisWebNavSettings = new WebNavigationSettings(context, web);

            context.Load(thisWebNavSettings);
            context.ExecuteQueryWithTrace();

            return thisWebNavSettings;
        }
Beispiel #3
0
        protected ClientObjectList<AppInstance> FindExistingApps(WebModelHost webHost, AppDefinition appModel)
        {
            TraceService.VerboseFormat((int)LogEventId.ModelProvisionCoreCall, "FindExistingApps() - finding app by productId: [{0}]", appModel.ProductId);

            var context = webHost.HostWeb.Context;
            var result = webHost.HostWeb.GetAppInstancesByProductId(appModel.ProductId);

            context.Load(result);
            context.ExecuteQueryWithTrace();

            return result;
        }
        protected List<ListItem> LoadPageLayouts(WebModelHost webModelHost)
        {
            var rootWeb = webModelHost.HostSite.RootWeb;
            var context = rootWeb.Context;

            var masterPageList = rootWeb.QueryAndGetListByUrl("/_catalogs/masterpage");

            var pageLayouts = masterPageList.GetItems(CamlQueryTemplates.ItemsByFieldValueBeginsWithQuery("ContentTypeId", BuiltInPublishingContentTypeId.PageLayout));
            context.Load(pageLayouts);
            context.ExecuteQueryWithTrace();

            return pageLayouts.ToList();
        }
        private void DeployClearRecycleUnderWeb(object modelHost, WebModelHost typedModelHost, ClearRecycleBinDefinition typedDefinition)
        {
            var web = typedModelHost.HostWeb;

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

            if (typedDefinition.RestoreAll)
            {
                web.RecycleBin.RestoreAll();
                web.Context.ExecuteQueryWithTrace();
            }

            if (typedDefinition.DeleteAll)
            {
                web.RecycleBin.DeleteAll();
                web.Context.ExecuteQueryWithTrace();
            }

            // TODO, CSOM limitations?
            if (typedDefinition.MoveAllToSecondStage)
            {

            }

            // TODO, CSOM limitations?
            if (typedDefinition.DeleteAllInSecondStage)
            {

            }

            InvokeOnModelEvent(this, new ModelEventArgs
            {
                CurrentModelNode = null,
                Model = null,
                EventType = ModelEventType.OnProvisioned,
                Object = web,
                ObjectType = typeof(Web),
                ObjectDefinition = typedDefinition,
                ModelHost = modelHost
            });
        }
        private void ProcessConverBlankSpacesIntoHyphenSetting(
            WebModelHost webModelHost,
            PublishingWeb publishingWeb,
            PageLayoutAndSiteTemplateSettingsDefinition definition,
            List<ListItem> pageLayouts)
        {
            var web = publishingWeb.Web;

            var key = "__AllowSpacesInNewPageName";
            var value = definition.ConverBlankSpacesIntoHyphen.HasValue
                ? definition.ConverBlankSpacesIntoHyphen.ToString()
                : false.ToString();

            SetPropertyBagValue(web, key, value);
        }
        protected virtual AppPrincipal FindExistingAppPrincipal(WebModelHost webHost, AppPrincipalDefinition appPrincipalModel)
        {
            var context = webHost.HostWeb.Context;
            //var context = webHost.HostclientContext;

            var appPrincipalManager = AppPrincipalManager.GetManager(context, webHost.HostWeb);
            var appPrincipalProvider = AppPrincipalIdentityProvider.GetExternal(context);

            var appPrincipalName = AppPrincipalName.CreateFromAppPrincipalIdentifier(context, appPrincipalModel.AppId);
            var result = appPrincipalManager.LookupAppPrincipal(appPrincipalProvider, appPrincipalName);

            context.Load(result);
            context.ExecuteQueryWithTrace();

            return result;
        }
Beispiel #8
0
        protected Field FindExistingWebField(WebModelHost siteModelHost, FieldDefinition fieldDefinition)
        {
            var id = fieldDefinition.Id;
            var rootWeb = siteModelHost.HostWeb;

            TraceService.VerboseFormat((int)LogEventId.ModelProvisionCoreCall, "FindExistingSiteField with Id: [{0}]", id);

            var context = rootWeb.Context;
            var scope = new ExceptionHandlingScope(context);

            Field field = null;

            using (scope.StartScope())
            {
                using (scope.StartTry())
                {
                    rootWeb.Fields.GetById(id);
                }

                using (scope.StartCatch())
                {

                }
            }

            TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "ExecuteQuery()");
            context.ExecuteQueryWithTrace();

            if (!scope.HasException)
            {
                field = rootWeb.Fields.GetById(id);
                context.Load(field);

                TraceService.VerboseFormat((int)LogEventId.ModelProvisionCoreCall, "Found site field with Id: [{0}]", id);
                TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "ExecuteQuery()");

                context.ExecuteQueryWithTrace();
            }
            else
            {
                TraceService.VerboseFormat((int)LogEventId.ModelProvisionCoreCall, "Cannot find site field with Id: [{0}]", id);
            }

            return field;
        }
        private void DeployDefinition(object modelHost, WebModelHost typedModelHost, DeleteTopNavigationNodesDefinition typedDefinition)
        {
            var web = typedModelHost.HostWeb;
            var context = web.Context;

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

            if (typedDefinition.NavigationNodes != null && typedDefinition.NavigationNodes.Any())
            {
                var nodesCollection = GetNavigationNodeCollection(web);

                context.Load(nodesCollection);
                context.ExecuteQueryWithTrace();

                DeleteNavigationNodesService.DeleteNodesByMatch(typedDefinition, nodesCollection, url =>
                {
                    return ResolveTokenizedUrl(typedModelHost, url);
                });
            }

            InvokeOnModelEvent(this, new ModelEventArgs
            {
                CurrentModelNode = null,
                Model = null,
                EventType = ModelEventType.OnProvisioned,
                Object = web,
                ObjectType = typeof(Web),
                ObjectDefinition = typedDefinition,
                ModelHost = modelHost
            });
        }
        private void DeployDefinition(object modelHost, WebModelHost webModelHost, PageLayoutAndSiteTemplateSettingsDefinition definition)
        {
            var web = webModelHost.HostWeb;
            var context = web.Context;

            var publishingWeb = PublishingWeb.GetPublishingWeb(context, web);

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

            var pageLayouts = LoadPageLayouts(webModelHost);

            ProcessWebTemplateSettings(webModelHost, publishingWeb, definition, pageLayouts);
            ProcessPageLayoutSettings(webModelHost, publishingWeb, definition, pageLayouts);
            ProcessNewPageDefaultSettings(webModelHost, publishingWeb, definition, pageLayouts);
            ProcessConverBlankSpacesIntoHyphenSetting(webModelHost, publishingWeb, definition, pageLayouts);

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

            web.Update();
            context.ExecuteQueryWithTrace();
        }
 private void DeployWebEventReceiver(object modelHost, WebModelHost listModelHost, EventReceiverDefinition definition)
 {
     DeployEventReceiver(modelHost, listModelHost.HostWeb.EventReceivers, definition);
 }
        protected NavigationNode GetRootNavigationNode(
            WebModelHost webModelHost,
            QuickLaunchNavigationNodeDefinition quickLaunchModel)
        {
            NavigationNodeCollection quickLaunch = null;
            var result = GetRootNavigationNode(webModelHost, quickLaunchModel, out quickLaunch);

            return result;
        }
        private NavigationNode EnsureRootQuickLaunchNavigationNode(
            WebModelHost webModelHost,
            QuickLaunchNavigationNodeDefinition quickLaunchModel)
        {
            NavigationNodeCollection quickLaunch = null;

            var context = webModelHost.HostWeb.Context;

            var existingNode = GetRootNavigationNode(webModelHost, quickLaunchModel, out quickLaunch);
            var previousNode = quickLaunch.Count > 0 ? quickLaunch.Last() : null;

            InvokeOnModelEvent(this, new ModelEventArgs
            {
                CurrentModelNode = null,
                Model = null,
                EventType = ModelEventType.OnProvisioning,
                Object = existingNode,
                ObjectType = typeof(NavigationNode),
                ObjectDefinition = quickLaunchModel,
                ModelHost = webModelHost
            });

            if (existingNode == null)
            {
                existingNode = quickLaunch.Add(new NavigationNodeCreationInformation
                {
                    Title = quickLaunchModel.Title,
                    IsExternal = quickLaunchModel.IsExternal,
                    Url = quickLaunchModel.Url,
                    PreviousNode = previousNode
                });

                context.ExecuteQuery();
            }

            existingNode.Title = quickLaunchModel.Title;
            existingNode.Url = quickLaunchModel.Url;
            existingNode.IsVisible = quickLaunchModel.IsVisible;

            InvokeOnModelEvent(this, new ModelEventArgs
            {
                CurrentModelNode = null,
                Model = null,
                EventType = ModelEventType.OnProvisioned,
                Object = existingNode,
                ObjectType = typeof(NavigationNode),
                ObjectDefinition = quickLaunchModel,
                ModelHost = webModelHost
            });

            existingNode.Update();

            context.ExecuteQuery();

            return existingNode;
        }
        protected NavigationNode GetRootNavigationNode(
            WebModelHost webModelHost,
            QuickLaunchNavigationNodeDefinition quickLaunchModel, out NavigationNodeCollection quickLaunch)
        {
            var web = webModelHost.HostWeb;
            var context = webModelHost.HostWeb.Context;

            quickLaunch = web.Navigation.QuickLaunch;

            context.Load(quickLaunch);
            context.ExecuteQuery();

            var existingNode = quickLaunch.OfType<NavigationNode>()
                .FirstOrDefault(n => n.Url == quickLaunchModel.Url);

            return existingNode;
        }
Beispiel #15
0
        protected virtual ListTemplate ResolveListTemplate(WebModelHost host, ListDefinition listModel)
        {
            var context = host.HostClientContext;

            var site = host.HostSite;
            var web = host.HostWeb;

            // internal names would be with '.STP', so just a little bit easier to define and find
            var templateName = listModel.TemplateName.ToUpper().Replace(".STP", string.Empty);

            TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "Fetching all web.ListTemplates");

            context.Load(web, tmpWeb => tmpWeb.ListTemplates);
            context.ExecuteQueryWithTrace();

            var listTemplate = web.ListTemplates
                                  .FirstOrDefault(t => t.InternalName.ToUpper().Replace(".STP", string.Empty) == templateName);

            if (listTemplate == null)
            {
                TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall,
                    "Searching list template in Site.GetCustomListTemplates(web)");

                var customListTemplates = site.GetCustomListTemplates(web);
                context.Load(customListTemplates);
                context.ExecuteQueryWithTrace();

                listTemplate = customListTemplates
                                  .FirstOrDefault(t => t.InternalName.ToUpper().Replace(".STP", string.Empty) == templateName);
            }

            if (listTemplate == null)
            {
                throw new SPMeta2Exception(string.Format("Can't find custom list template with internal Name:[{0}]",
                    listModel.TemplateName));
            }
            return listTemplate;
        }
Beispiel #16
0
        private void DeployApp(object modelHost, WebModelHost webHost, AppDefinition appModel)
        {
            var web = webHost.HostWeb;
            var context = web.Context;

            var appId = Guid.Empty;

            TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "Creating memory stream on appModel.Content");

            using (var appPackage = new MemoryStream(appModel.Content))
            {
                var currentApplications = FindExistingApps(webHost, appModel);

                InvokeOnModelEvent(this, new ModelEventArgs
                {
                    CurrentModelNode = null,
                    Model = null,
                    EventType = ModelEventType.OnProvisioning,
                    Object = currentApplications.FirstOrDefault(),
                    ObjectType = typeof(AppInstance),
                    ObjectDefinition = appModel,
                    ModelHost = modelHost
                });


                if (currentApplications == null || currentApplications.Count == 0)
                {
                    TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "Cannot find application by productId. Loading and installing new instance.");

                    // install new
                    var newAppInstance = web.LoadAndInstallApp(appPackage);



                    context.Load(newAppInstance);
                    context.ExecuteQueryWithTrace();

                    if (newAppInstance != null && newAppInstance.Status == AppInstanceStatus.Initialized)
                    {
                        appId = newAppInstance.Id;

                        var count = 0;
                        AppInstance localInstance = null;

                        do
                        {
                            TraceService.VerboseFormat((int)LogEventId.ModelProvisionCoreCall,
                                "Waiting while app is being installed for [{0}] milliseconds.",
                                WaitTimeInMillliseconds);

                            Thread.Sleep(WaitTimeInMillliseconds);
                            localInstance = web.GetAppInstanceById(appId);

                            context.Load(localInstance, l => l.Status);
                            context.ExecuteQueryWithTrace();

                            count++;
                        } while (localInstance != null &&
                                 localInstance.Status != AppInstanceStatus.Installed &&
                                 count < MaxInstallAttempCount);
                    }

                    newAppInstance = web.GetAppInstanceById(appId);

                    InvokeOnModelEvent(this, new ModelEventArgs
                    {
                        CurrentModelNode = null,
                        Model = null,
                        EventType = ModelEventType.OnProvisioned,
                        Object = newAppInstance,
                        ObjectType = typeof(AppInstance),
                        ObjectDefinition = appModel,
                        ModelHost = modelHost
                    });
                }
                else
                {
                    //we had check early
                    var currentApp = currentApplications.FirstOrDefault();

                    TraceService.Information((int)LogEventId.ModelProvisionProcessingExistingObject,
                        string.Format("Processing existing application. Upgrading from [{0}] to [{1}]", currentApp.Title, appModel.Version));

                    var hasUpdate = false;

                    for (int i = 0; i < currentApplications.Count; i++)
                    {
                        var spApp = currentApplications[i];
                        //var spAppVersion = new Version(spApp.App.VersionString);

                        var definitionVersion = new Version(appModel.Version);

                        // always install
                        //if (definitionVersion > spAppVersion)
                        //{
                        TraceService.Information((int)LogEventId.ModelProvisionProcessingExistingObject, "Performing upgrade");

                        var updateAppInstance = currentApplications[i];
                        var updateAppId = updateAppInstance.Id;

                        var count = 0;
                        AppInstance localUpdateAppInstance = null;

                        try
                        {
                            updateAppInstance.Upgrade(appPackage);
                            context.ExecuteQueryWithTrace();
                        }
                        catch (Exception upgradeException)
                        {
                            // handling early version upgrades
                            // Microsoft.SharePoint.Client.ServerException]	
                            // {"An App Instance can only be upgraded to a newer version of the same product. The upgrade request was for product 1.0.0.3 version e81b6820-5d57-4d17-a098-5f4317f6c400 to product 1.0.0.0 version e81b6820-5d57-4d17-a098-5f4317f6c400."}

                            if (IsAppUpgradeException(upgradeException))
                            {
                                // fascinating
                                // jumping to the happy end
                                goto AppShouldNotBeUpdated;
                            }

                            throw;
                        }

                        do
                        {
                            TraceService.VerboseFormat((int)LogEventId.ModelProvisionCoreCall,
                                "Waiting while app is being installed for [{0}] milliseconds.",
                                WaitTimeInMillliseconds);

                            Thread.Sleep(WaitTimeInMillliseconds);
                            localUpdateAppInstance = web.GetAppInstanceById(updateAppId);

                            context.Load(localUpdateAppInstance, l => l.Status);
                            context.ExecuteQueryWithTrace();

                            count++;
                        } while (localUpdateAppInstance != null &&
                                 localUpdateAppInstance.Status != AppInstanceStatus.Installed &&
                                 count < MaxInstallAttempCount);

                        hasUpdate = true;

                        //}
                        //else
                        //{
                        //    TraceService.Information((int)LogEventId.ModelProvisionProcessingExistingObject, "Skipping upgrade due to the lower version");
                        //}
                    }

                    if (hasUpdate)
                    {
                        // refreshing the app collection after update
                        // the .App.VersionString property will be refreshed
                        currentApplications = FindExistingApps(webHost, appModel);
                    }

                AppShouldNotBeUpdated:

                    InvokeOnModelEvent(this, new ModelEventArgs
                    {
                        CurrentModelNode = null,
                        Model = null,
                        EventType = ModelEventType.OnProvisioned,
                        Object = currentApplications.FirstOrDefault(),
                        ObjectType = typeof(AppInstance),
                        ObjectDefinition = appModel,
                        ModelHost = modelHost
                    });
                }
            }
        }
Beispiel #17
0
        private static Web GetParentWeb(WebModelHost csomModelHost)
        {
            Web parentWeb = null;

            if (csomModelHost.HostWeb != null)
                parentWeb = csomModelHost.HostWeb;
            else if (csomModelHost.HostSite != null)
                parentWeb = csomModelHost.HostSite.RootWeb;
            else
                throw new ArgumentException("modelHost");

            return parentWeb;
        }
        private static void ProcessPageLayoutSettings(
            WebModelHost webModelHost,
            PublishingWeb publishingWeb,
            PageLayoutAndSiteTemplateSettingsDefinition definition,
            List<ListItem> pageLayouts)
        {
            var rootWeb = webModelHost.HostSite.RootWeb;
            var web = publishingWeb.Web;
            var context = web.Context;

            if (definition.InheritPageLayouts.HasValue && definition.InheritPageLayouts.Value)
            {
                SetPropertyBagValue(web, "__PageLayouts", "__inherit");
            }
            else if (definition.UseAnyPageLayout.HasValue && definition.UseAnyPageLayout.Value)
            {
                SetPropertyBagValue(web, "__PageLayouts", "");
            }
            else if (definition.UseDefinedPageLayouts.HasValue && definition.UseDefinedPageLayouts.Value)
            {
                var selectedPageLayouts = new List<ListItem>();

                foreach (var selectedLayoutName in definition.DefinedPageLayouts)
                {
                    var targetLayout = pageLayouts.FirstOrDefault(t => t["FileLeafRef"].ToString().ToUpper() == selectedLayoutName.ToUpper());

                    if (targetLayout != null)
                        selectedPageLayouts.Add(targetLayout);
                }

                if (selectedPageLayouts.Any())
                {
                    var resultString = CreateLayoutsXmlString(selectedPageLayouts,rootWeb.ServerRelativeUrl);
                    SetPropertyBagValue(web, "__PageLayouts", resultString);
                }
            }
        }
        private void DeployWorkflowDefinition(WebModelHost host,
            Web web,
            SP2013WorkflowDefinition workflowDefinitionModel)
        {
            var clientContext = web.Context;

            var workflowServiceManager = new WorkflowServicesManager(clientContext, web);
            var workflowDeploymentService = workflowServiceManager.GetWorkflowDeploymentService();

            var currentWorkflowDefinition = GetCurrentWorkflowDefinition(web, workflowDefinitionModel);

            InvokeOnModelEvent(this, new ModelEventArgs
            {
                CurrentModelNode = null,
                Model = null,
                EventType = ModelEventType.OnProvisioning,
                Object = currentWorkflowDefinition,
                ObjectType = typeof(WorkflowDefinition),
                ObjectDefinition = workflowDefinitionModel,
                ModelHost = host
            });

            if (currentWorkflowDefinition == null)
            {
                TraceService.Information((int)LogEventId.ModelProvisionProcessingNewObject, "Processing new SP2013 workflow definition");

                var workflowDefinition = new WorkflowDefinition(clientContext)
                {
                    Xaml = workflowDefinitionModel.Xaml,
                    DisplayName = workflowDefinitionModel.DisplayName
                };

                clientContext.Load(workflowDefinition);

                MapProperties(workflowDefinition, workflowDefinitionModel);

                InvokeOnModelEvent(this, new ModelEventArgs
                {
                    CurrentModelNode = null,
                    Model = null,
                    EventType = ModelEventType.OnProvisioned,
                    Object = workflowDefinition,
                    ObjectType = typeof(WorkflowDefinition),
                    ObjectDefinition = workflowDefinitionModel,
                    ModelHost = host
                });

                TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "Calling SaveDefinition()");
                workflowDeploymentService.SaveDefinition(workflowDefinition);
                clientContext.ExecuteQueryWithTrace();

                TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "Calling PublishDefinition()");
                workflowDeploymentService.PublishDefinition(workflowDefinition.Id);
                clientContext.ExecuteQueryWithTrace();
            }
            else
            {
                TraceService.Information((int)LogEventId.ModelProvisionProcessingExistingObject, "Processing existing SP2013 workflow definition");

                if (workflowDefinitionModel.Override)
                {
                    TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "Override = true. Overriding workflow definition");

                    currentWorkflowDefinition.Xaml = workflowDefinitionModel.Xaml;

                    MapProperties(currentWorkflowDefinition, workflowDefinitionModel);

                    InvokeOnModelEvent(this, new ModelEventArgs
                    {
                        CurrentModelNode = null,
                        Model = null,
                        EventType = ModelEventType.OnProvisioned,
                        Object = currentWorkflowDefinition,
                        ObjectType = typeof(WorkflowDefinition),
                        ObjectDefinition = workflowDefinitionModel,
                        ModelHost = host
                    });

                    TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "Calling SaveDefinition()");
                    workflowDeploymentService.SaveDefinition(currentWorkflowDefinition);

                    TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "Calling PublishDefinition()");
                    workflowDeploymentService.PublishDefinition(currentWorkflowDefinition.Id);

                    clientContext.ExecuteQueryWithTrace();
                }
                else
                {
                    TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "Override = false. Skipping workflow definition");

                    MapProperties(currentWorkflowDefinition, workflowDefinitionModel);

                    InvokeOnModelEvent(this, new ModelEventArgs
                    {
                        CurrentModelNode = null,
                        Model = null,
                        EventType = ModelEventType.OnProvisioned,
                        Object = currentWorkflowDefinition,
                        ObjectType = typeof(WorkflowDefinition),
                        ObjectDefinition = workflowDefinitionModel,
                        ModelHost = host
                    });

                    TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "Calling PublishDefinition()");
                    workflowDeploymentService.PublishDefinition(currentWorkflowDefinition.Id);

                    clientContext.ExecuteQueryWithTrace();
                }
            }
        }
        private static void ProcessNewPageDefaultSettings(
            WebModelHost webModelHost,
            PublishingWeb publishingWeb,
            PageLayoutAndSiteTemplateSettingsDefinition definition,
            List<ListItem> pageLayouts)
        {
            var web = publishingWeb.Web;
            var context = web.Context;

            if (definition.InheritDefaultPageLayout.HasValue && definition.InheritDefaultPageLayout.Value)
            {
                SetPropertyBagValue(web, "__DefaultPageLayout", "__inherit");
            }
            else if (definition.UseDefinedDefaultPageLayout.HasValue && definition.UseDefinedDefaultPageLayout.Value)
            {
                var selectedLayoutName = definition.DefinedDefaultPageLayout;
                var targetLayout = pageLayouts.FirstOrDefault(t => t["FileLeafRef"].ToString().ToUpper() == selectedLayoutName.ToUpper());

                if (targetLayout != null)
                {
                    var resultString = CreateLayoutXmlString(targetLayout, webModelHost.HostSite.RootWeb.ServerRelativeUrl);
                    SetPropertyBagValue(web, "__DefaultPageLayout", resultString);
                }
            }
        }
        private void ApplyComposedLookUnderWeb(object modelHost, WebModelHost typedModelHost, ComposedLookItemLinkDefinition typedDefinition)
        {
            var web = typedModelHost.HostWeb;
            var rootWeb = typedModelHost.HostSite.RootWeb;

            var context = web.Context;
            var serverRelatieSiteUrl = typedModelHost.HostSite.ServerRelativeUrl;

            var composedLookName = typedDefinition.ComposedLookItemName;

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

            var composedLookList = web.GetCatalog((int)ListTemplateType.DesignCatalog);
            var items = composedLookList.GetItems(CamlQueryTemplates.ItemByFieldValueQuery("Name", composedLookName));

            context.Load(items);
            context.ExecuteQueryWithTrace();

            var targetComposedLookItem = items.Count > 0 ? items[0] : null;

            if (targetComposedLookItem == null)
                throw new SPMeta2Exception(string.Format("Can't find composed look by name: [{0}]", composedLookName));

            var name = ConvertUtils.ToString(targetComposedLookItem["Name"]);

            var masterPageUrl = GetUrlValue(targetComposedLookItem, "MasterPageUrl");

            if (!string.IsNullOrEmpty(masterPageUrl))
            {
                // server relative fun
                var targetMasterPageUrl = UrlUtility.CombineUrl(new[]
                {
                    web.ServerRelativeUrl,
                    "_catalogs/masterpage",
                    Path.GetFileName(masterPageUrl)
                });

                web.CustomMasterUrl = targetMasterPageUrl;
                web.MasterUrl = targetMasterPageUrl;

                web.Update();
                context.ExecuteQueryWithTrace();
            }

            var themeUrl = GetUrlValue(targetComposedLookItem, "ThemeUrl");
            var fontSchemeUrl = GetUrlValue(targetComposedLookItem, "FontSchemeUrl");
            var imageUrl = GetUrlValue(targetComposedLookItem, "ImageUrl");

            themeUrl = GetServerRelativeUrlFromFullUrl(serverRelatieSiteUrl, themeUrl);
            fontSchemeUrl = GetServerRelativeUrlFromFullUrl(serverRelatieSiteUrl, fontSchemeUrl);
            imageUrl = GetServerRelativeUrlFromFullUrl(serverRelatieSiteUrl, imageUrl);

            web.ApplyTheme(themeUrl,
                          !string.IsNullOrEmpty(fontSchemeUrl) ? fontSchemeUrl : null,
                          !string.IsNullOrEmpty(imageUrl) ? imageUrl : null,
                          false);

            context.ExecuteQueryWithTrace();

            InvokeOnModelEvent(this, new ModelEventArgs
            {
                CurrentModelNode = null,
                Model = null,
                EventType = ModelEventType.OnProvisioned,
                Object = web,
                ObjectType = typeof(Web),
                ObjectDefinition = typedDefinition,
                ModelHost = modelHost
            });

            // cirrent web was updated by theme engine
            // http://ehikioya.com/apply-themes-to-sharepoint/ 
            typedModelHost.ShouldUpdateHost = false;
        }
        private void ValidateRootQuickLaunchNavigationNode(WebModelHost webModelHost, QuickLaunchNavigationNodeDefinition quickLaunchModel)
        {
            var qlNode = GetRootNavigationNode(webModelHost, quickLaunchModel);

            ValidateNode(qlNode, quickLaunchModel);
        }
        private void DeployMasterPageSettings(object modelHost, WebModelHost webModelHost, MasterPageSettingsDefinition masterPageSettings)
        {
            var site = webModelHost.HostSite;
            var web = webModelHost.HostWeb;

            var sContext = site.Context;
            sContext.Load(site, s => s.ServerRelativeUrl);
            sContext.ExecuteQueryWithTrace();

            var siteRelativeUrl = site.ServerRelativeUrl;

            TraceService.VerboseFormat((int)LogEventId.ModelProvisionCoreCall, "Resolving server relative URL: [{0}]", siteRelativeUrl);

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

            // TODO, https://github.com/SubPointSolutions/spmeta2/issues/761
            // re-implement with native prop bag to suport SP2010
            // SP2010 CSOM does not have CustomMasterUrl / MasterUrl props

            #if !NET35

            if (!string.IsNullOrEmpty(masterPageSettings.SiteMasterPageUrl))
            {
                TraceService.VerboseFormat((int)LogEventId.ModelProvisionCoreCall, "Setting web.MasterUrlL: [{0}]", masterPageSettings.SiteMasterPageUrl);
                web.CustomMasterUrl = UrlUtility.CombineUrl(siteRelativeUrl, masterPageSettings.SiteMasterPageUrl);
            }

            if (!string.IsNullOrEmpty(masterPageSettings.SystemMasterPageUrl))
            {
                TraceService.VerboseFormat((int)LogEventId.ModelProvisionCoreCall, "Setting web.CustomMasterUrl: [{0}]", masterPageSettings.SystemMasterPageUrl);
                web.MasterUrl = UrlUtility.CombineUrl(siteRelativeUrl, masterPageSettings.SystemMasterPageUrl);
            }

            #endif

            if (!string.IsNullOrEmpty(masterPageSettings.SiteMasterPageUrl) ||
                !string.IsNullOrEmpty(masterPageSettings.SystemMasterPageUrl))
            {
                InvokeOnModelEvent(this, new ModelEventArgs
                {
                    CurrentModelNode = null,
                    Model = null,
                    EventType = ModelEventType.OnProvisioned,
                    Object = web,
                    ObjectType = typeof(Web),
                    ObjectDefinition = masterPageSettings,
                    ModelHost = modelHost
                });

                TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "Calling web.Update()");
                web.Update();

                web.Context.ExecuteQueryWithTrace();
            }
            else
            {
                InvokeOnModelEvent(this, new ModelEventArgs
                {
                    CurrentModelNode = null,
                    Model = null,
                    EventType = ModelEventType.OnProvisioned,
                    Object = web,
                    ObjectType = typeof(Web),
                    ObjectDefinition = masterPageSettings,
                    ModelHost = modelHost
                });
            }
        }
        private void DeployNavigationSettings(object modelHost, WebModelHost webModelHost, WebNavigationSettingsDefinition navigationModel)
        {
            var shouldUpdateWeb = false;

            var site = webModelHost.HostSite;
            var web = webModelHost.HostWeb;

            var context = web.Context;
            var allProperties = web.AllProperties;

            context.Load(allProperties);

            // the GetWebNavigationSettings will call ExecuteQueryWithTrace
            var thisWebNavSettings = GetWebNavigationSettings(webModelHost, navigationModel);

            StandardNavigationSource? globalSource = null;
            StandardNavigationSource? currentSource = null;

            if (!string.IsNullOrEmpty(navigationModel.GlobalNavigationSource))
                globalSource = (StandardNavigationSource)Enum.Parse(typeof(StandardNavigationSource), navigationModel.GlobalNavigationSource);

            if (!string.IsNullOrEmpty(navigationModel.CurrentNavigationSource))
                currentSource = (StandardNavigationSource)Enum.Parse(typeof(StandardNavigationSource), navigationModel.CurrentNavigationSource);

            TermStore currentTermStore = null;
            TermSet currentTermSet = null;

            if (currentSource == StandardNavigationSource.TaxonomyProvider)
            {
                currentTermStore = TaxonomyTermStoreModelHandler.FindTermStore(site,
                           navigationModel.CurrentNavigationTermStoreName,
                           navigationModel.CurrentNavigationTermStoreId,
                           navigationModel.CurrentNavigationUseDefaultSiteCollectionTermStore);

                currentTermSet = TaxonomyFieldModelHandler.LookupTermSet(currentTermStore.Context,
                  currentTermStore,
                  site,
                  null,
                  null,
                  null,
                  navigationModel.CurrentNavigationTermSetName,
                  navigationModel.CurrentNavigationTermSetId,
                  navigationModel.CurrentNavigationTermSetLCID);
            }

            TermStore globalTermStore = null;
            TermSet globalTermSet = null;

            if (globalSource == StandardNavigationSource.TaxonomyProvider)
            {
                globalTermStore = TaxonomyTermStoreModelHandler.FindTermStore(site,
                          navigationModel.GlobalNavigationTermStoreName,
                          navigationModel.GlobalNavigationTermStoreId,
                          navigationModel.GlobalNavigationUseDefaultSiteCollectionTermStore);

                globalTermSet = TaxonomyFieldModelHandler.LookupTermSet(site.Context,
                  globalTermStore,
                  site,
                  null,
                  null,
                  null,
                  navigationModel.GlobalNavigationTermSetName,
                  navigationModel.GlobalNavigationTermSetId,
                  navigationModel.GlobalNavigationTermSetLCID);
            }

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

            if (!string.IsNullOrEmpty(navigationModel.GlobalNavigationSource) ||
                !string.IsNullOrEmpty(navigationModel.CurrentNavigationSource))
            {
                if (globalSource.HasValue)
                {
                    TraceService.VerboseFormat((int)LogEventId.ModelProvisionCoreCall, "Setting GlobalNavigation to: [{0}]", navigationModel.GlobalNavigationSource);

                    thisWebNavSettings.GlobalNavigation.Source = globalSource.Value;

                    if (globalTermStore != null)
                    {
                        thisWebNavSettings.GlobalNavigation.TermStoreId = globalTermStore.Id;
                        thisWebNavSettings.GlobalNavigation.TermSetId = globalTermSet.Id;
                    }
                    else
                    {
                        var value = allProperties.FieldValues.ContainsKey(BuiltInWebPropertyId.GlobalNavigationIncludeTypes)
                                        ? allProperties[BuiltInWebPropertyId.GlobalNavigationIncludeTypes]
                                        : string.Empty;

                        int? globalNavigationIncludeTypes = GetGlobalNavigationIncludeTypes(
                                    navigationModel,
                                    ConvertUtils.ToInt(value));

                        if (globalNavigationIncludeTypes != null)
                        {
                            TraceService.VerboseFormat((int)LogEventId.ModelProvisionCoreCall, "Setting GlobalNavigationIncludeTypes to: [{0}]", globalNavigationIncludeTypes);
                            allProperties[BuiltInWebPropertyId.GlobalNavigationIncludeTypes] = globalNavigationIncludeTypes.Value;

                            shouldUpdateWeb = true;
                        }

                        if (navigationModel.GlobalNavigationMaximumNumberOfDynamicItems.HasValue)
                        {
                            TraceService.VerboseFormat((int)LogEventId.ModelProvisionCoreCall, "Setting GlobalDynamicChildLimit to: [{0}]", navigationModel.GlobalNavigationMaximumNumberOfDynamicItems.Value);
                            allProperties[BuiltInWebPropertyId.GlobalDynamicChildLimit] = navigationModel.GlobalNavigationMaximumNumberOfDynamicItems.Value;

                            shouldUpdateWeb = true;
                        }
                    }
                }

                if (currentSource.HasValue)
                {
                    TraceService.VerboseFormat((int)LogEventId.ModelProvisionCoreCall,
                        "Setting CurrentNavigation to: [{0}]", navigationModel.CurrentNavigationSource);

                    thisWebNavSettings.CurrentNavigation.Source = currentSource.Value;

                    if (currentTermStore != null)
                    {
                        thisWebNavSettings.CurrentNavigation.TermStoreId = currentTermStore.Id;
                        thisWebNavSettings.CurrentNavigation.TermSetId = currentTermSet.Id;
                    }
                    else
                    {
                        var value = allProperties.FieldValues.ContainsKey(BuiltInWebPropertyId.CurrentNavigationIncludeTypes)
                                        ? allProperties[BuiltInWebPropertyId.CurrentNavigationIncludeTypes]
                                        : string.Empty;


                        int? currentNavigationIncludeTypes = GetCurrentNavigationIncludeTypes(
                            navigationModel,
                            ConvertUtils.ToInt(value));

                        if (currentNavigationIncludeTypes != null)
                        {
                            TraceService.VerboseFormat((int)LogEventId.ModelProvisionCoreCall, "Setting CurrentNavigationIncludeTypes to: [{0}]", currentNavigationIncludeTypes);
                            allProperties[BuiltInWebPropertyId.CurrentNavigationIncludeTypes] = currentNavigationIncludeTypes.Value;

                            shouldUpdateWeb = true;
                        }

                        if (navigationModel.CurrentNavigationMaximumNumberOfDynamicItems.HasValue)
                        {
                            TraceService.VerboseFormat((int)LogEventId.ModelProvisionCoreCall, "Setting CurrentDynamicChildLimit to: [{0}]", navigationModel.CurrentNavigationMaximumNumberOfDynamicItems.Value);
                            allProperties[BuiltInWebPropertyId.CurrentDynamicChildLimit] = navigationModel.CurrentNavigationMaximumNumberOfDynamicItems.Value;

                            shouldUpdateWeb = true;
                        }
                    }
                }

            }

            if (navigationModel.DisplayShowHideRibbonAction.HasValue)
            {
                allProperties["__DisplayShowHideRibbonActionId"] = navigationModel.DisplayShowHideRibbonAction.ToString();
                shouldUpdateWeb = true;
            }

            InvokeOnModelEvent(this, new ModelEventArgs
            {
                CurrentModelNode = null,
                Model = null,
                EventType = ModelEventType.OnProvisioned,
                Object = thisWebNavSettings,
                ObjectType = typeof(WebNavigationSettings),
                ObjectDefinition = navigationModel,
                ModelHost = modelHost
            });

            if (!string.IsNullOrEmpty(navigationModel.GlobalNavigationSource) ||
                !string.IsNullOrEmpty(navigationModel.CurrentNavigationSource))
            {
                TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "Updating navigation settings");

                web.Update();
                thisWebNavSettings.Update(null);
                shouldUpdateWeb = true;
            }

            if (shouldUpdateWeb)
            {
                TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "Updating web");
                web.Update();
                context.ExecuteQueryWithTrace();
            }
        }
        private void DeployAppPrincipal(object modelHost, WebModelHost webHost, AppPrincipalDefinition appPrincipalModel)
        {
            var context = webHost.HostWeb.Context;

            var appPrincipalManager = AppPrincipalManager.GetManager(context, webHost.HostWeb);
            var principal = FindExistingAppPrincipal(webHost, appPrincipalModel);

            context.ExecuteQueryWithTrace();

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


            if (principal == null)
            {
                var endpoints = new List<string>();
                endpoints.Add(appPrincipalModel.RedirectURI);

                var now = DateTime.Now;

                var credential = AppPrincipalCredential.CreateFromSymmetricKey(context, appPrincipalModel.AppSecret, now, now.AddYears(1));

                var externalAppPrincipalCreationParameters = new ExternalAppPrincipalCreationParameters()
                {
                    AppIdentifier = appPrincipalModel.AppId,
                    DisplayName = appPrincipalModel.Title,
                    Credential = credential,
                    ApplicationEndpointAuthorities = endpoints
                };

                principal = appPrincipalManager.CreateAppPrincipal(externalAppPrincipalCreationParameters);

                InvokeOnModelEvent(this, new ModelEventArgs
                {
                    CurrentModelNode = null,
                    Model = null,
                    EventType = ModelEventType.OnProvisioned,
                    Object = principal,
                    ObjectType = typeof(AppPrincipal),
                    ObjectDefinition = appPrincipalModel,
                    ModelHost = modelHost
                });
            }
            else
            {
                InvokeOnModelEvent(this, new ModelEventArgs
                {
                    CurrentModelNode = null,
                    Model = null,
                    EventType = ModelEventType.OnProvisioned,
                    Object = principal,
                    ObjectType = typeof(AppPrincipal),
                    ObjectDefinition = appPrincipalModel,
                    ModelHost = modelHost
                });
            }
        }
        private Field DeployWebField(WebModelHost webModelHost, FieldDefinition fieldModel)
        {
            TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "Deploying web field");

            var web = webModelHost.HostWeb;
            var context = web.Context;

            var field = GetField(webModelHost, fieldModel);

            return EnsureField(context, field, web.Fields, fieldModel);
        }
Beispiel #27
0
        public override void WithResolvingModelHost(ModelHostResolveContext modelHostContext)
        {
            var modelHost = modelHostContext.ModelHost as ModelHostBase;
            var model = modelHostContext.Model;
            var childModelType = modelHostContext.ChildModelType;
            var action = modelHostContext.Action;

            var parentWeb = ExtractWeb(modelHost);
            var hostclientContext = ExtractHostClientContext(modelHost);
            var hostSite = ExtractHostSite(modelHost);

            var webModel = model.WithAssertAndCast<WebDefinition>("model", value => value.RequireNotNull());

            var context = parentWeb.Context;

            context.Load(parentWeb, w => w.Url);
            //context.Load(parentWeb, w => w.RootFolder);
            context.Load(parentWeb, w => w.ServerRelativeUrl);
            context.ExecuteQueryWithTrace();

            var currentWebUrl = GetCurrentWebUrl(context, parentWeb, webModel);
            var currentWeb = GetExistingWeb(hostSite, parentWeb, currentWebUrl);

            InvokeOnModelEvent(this, new ModelEventArgs
            {
                CurrentModelNode = modelHostContext.ModelNode,
                Model = null,
                EventType = ModelEventType.OnModelHostResolving,
                Object = parentWeb,
                ObjectType = typeof(Web),
                ObjectDefinition = model,
                ModelHost = modelHost
            });

            var tmpWebModelHost = new WebModelHost
            {
                HostClientContext = hostclientContext,
                HostSite = hostSite,
                HostWeb = currentWeb
            };

            if (childModelType == typeof (ModuleFileDefinition))
            {
                var folderModelHost = ModelHostBase.Inherit<FolderModelHost>(modelHost, m =>
                {
                    m.CurrentWeb = currentWeb;
                    m.CurrentWebFolder = currentWeb.RootFolder; ;
                });

                action(folderModelHost);
            }
            else
            {
                action(tmpWebModelHost);
            }

            InvokeOnModelEvent(this, new ModelEventArgs
            {
                CurrentModelNode = modelHostContext.ModelNode,
                Model = null,
                EventType = ModelEventType.OnModelHostResolved,
                Object = parentWeb,
                ObjectType = typeof(Web),
                ObjectDefinition = model,
                ModelHost = modelHost
            });

            currentWeb.Update();
            context.ExecuteQueryWithTrace();
        }
        private void DeployWebWorkflowAssociationDefinition(WebModelHost modelHost, Web web, WorkflowAssociationDefinition definition)
        {
            var context = web.Context;
            var existingWorkflowAssotiation = FindExistringWorkflowAssotiation(modelHost, definition);

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

            if (existingWorkflowAssotiation == null
                ||
                (existingWorkflowAssotiation.ServerObjectIsNull.HasValue &&
                 existingWorkflowAssotiation.ServerObjectIsNull.Value))
            {
                var workflowTemplate = GetWorkflowTemplate(modelHost, definition);

                if (workflowTemplate == null ||
                    (workflowTemplate.ServerObjectIsNull.HasValue && workflowTemplate.ServerObjectIsNull.Value))
                {
                    throw new SPMeta2Exception(
                        string.Format("Cannot find workflow template by definition:[{0}]", definition));
                }

                var historyList = web.QueryAndGetListByTitle(definition.HistoryListTitle);
                var taskList = web.QueryAndGetListByTitle(definition.TaskListTitle);

                var newWorkflowAssotiation = web.WorkflowAssociations.Add(new WorkflowAssociationCreationInformation
                {
                    Name = definition.Name,
                    Template = workflowTemplate,
                    HistoryList = historyList,
                    TaskList = taskList
                });

                MapProperties(definition, newWorkflowAssotiation);

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

                web.Update();
                context.ExecuteQueryWithTrace();
            }
            else
            {
                MapProperties(definition, existingWorkflowAssotiation);

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

                // no update
                // gives weird null ref exception

                // Enhance WorkflowAssociationDefinition - add more tests on updatability #871
                // https://github.com/SubPointSolutions/spmeta2/issues/871

                //existingWorkflowAssotiation.Update();
                //web.Update();
                context.ExecuteQueryWithTrace();
            }
        }
        private static void ProcessWebTemplateSettings(
            WebModelHost webModelHost,
            PublishingWeb publishingWeb,
            PageLayoutAndSiteTemplateSettingsDefinition definition,
            List<ListItem> pageLayouts)
        {
            //var web = publishingWeb.Web;

            //if (definition.InheritWebTemplates.HasValue && definition.InheritWebTemplates.Value)
            //    publishingWeb.InheritAvailableWebTemplates();
            //else if (definition.UseAnyWebTemplate.HasValue && definition.UseAnyWebTemplate.Value)
            //{
            //    publishingWeb.AllowAllWebTemplates(definition.ResetAllSubsitesToInheritWebTemplates.HasValue
            //        ? definition.ResetAllSubsitesToInheritWebTemplates.Value
            //        : false);
            //}
            //else if (definition.UseDefinedWebTemplates.HasValue && definition.UseDefinedWebTemplates.Value)
            //{
            //    var currentLocaleId = (uint)web.CurrencyLocaleID;
            //    var webTemplates = new List<SPWebTemplate>();

            //    webTemplates.AddRange(web.Site.GetWebTemplates(currentLocaleId).OfType<SPWebTemplate>());
            //    webTemplates.AddRange(web.Site.GetCustomWebTemplates(currentLocaleId).OfType<SPWebTemplate>());

            //    var selectedWebTemplates = new Collection<SPWebTemplate>();

            //    foreach (var selectedWebTemplateName in definition.DefinedWebTemplates)
            //    {
            //        var targetWebTemplate =
            //            webTemplates.FirstOrDefault(t => t.Name.ToUpper() == selectedWebTemplateName.ToUpper());

            //        if (targetWebTemplate != null)
            //            selectedWebTemplates.Add(targetWebTemplate);
            //    }

            //    if (selectedWebTemplates.Any())
            //    {
            //        publishingWeb.SetAvailableWebTemplates(selectedWebTemplates, 0,
            //            definition.ResetAllSubsitesToInheritWebTemplates.HasValue
            //                ? definition.ResetAllSubsitesToInheritWebTemplates.Value
            //                : false);
            //    }
            //}
        }
Beispiel #30
0
        private void DeployApp(object modelHost, WebModelHost webHost, AppDefinition appModel)
        {
            var web = webHost.HostWeb;
            Guid appId = Guid.Empty;

            TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "Creating memory stream on appModel.Content");

            using (var appPackage = new MemoryStream(appModel.Content))
            {
                var currentApplications = FindExistingApps(webHost, appModel);

                InvokeOnModelEvent(this, new ModelEventArgs
                {
                    CurrentModelNode = null,
                    Model = null,
                    EventType = ModelEventType.OnProvisioning,
                    Object = currentApplications.FirstOrDefault(),
                    ObjectType = typeof(AppInstance),
                    ObjectDefinition = appModel,
                    ModelHost = modelHost
                });


                if (currentApplications == null || currentApplications.Count == 0)
                {
                    TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "Cannot find application by productId. Loading and installing new instance.");

                    // install new
                    var newAppInstance = web.LoadAndInstallApp(appPackage);

                    var context = web.Context;

                    context.Load(newAppInstance);
                    context.ExecuteQueryWithTrace();

                    if (newAppInstance != null && newAppInstance.Status == AppInstanceStatus.Initialized)
                    {
                        appId = newAppInstance.Id;

                        var count = 0;
                        AppInstance localInstance = null;

                        do
                        {
                            TraceService.VerboseFormat((int)LogEventId.ModelProvisionCoreCall,
                                "Waiting while app is being installed for [{0}] milliseconds.",
                                WaitTimeInMillliseconds);

                            Thread.Sleep(WaitTimeInMillliseconds);
                            localInstance = web.GetAppInstanceById(appId);

                            context.Load(localInstance, l => l.Status);
                            context.ExecuteQueryWithTrace();

                            count++;
                        } while (localInstance != null &&
                                 localInstance.Status != AppInstanceStatus.Installed &&
                                 count < MaxInstallAttempCount);
                    }

                    newAppInstance = web.GetAppInstanceById(appId);

                    InvokeOnModelEvent(this, new ModelEventArgs
                    {
                        CurrentModelNode = null,
                        Model = null,
                        EventType = ModelEventType.OnProvisioned,
                        Object = newAppInstance,
                        ObjectType = typeof(AppInstance),
                        ObjectDefinition = appModel,
                        ModelHost = modelHost
                    });
                }
                else
                {
                    TraceService.Information((int)LogEventId.ModelProvisionProcessingExistingObject, "Processing existing application. CSOM update is not supported yet.");

                    // R&D for update
                    // upApp.App is not available

                    //for (int i = 0; i < currentApplications.Count; i++)
                    //{
                    //    var upApp = currentApplications[i];
                    //    var upVersion = new Version(upApp.App.VersionString);

                    //    var targetVersion = new Version(appModel.Version);

                    //    if (upVersion < targetVersion)
                    //        currentApplications[i].Upgrade(appPackage);
                    //}

                    InvokeOnModelEvent(this, new ModelEventArgs
                    {
                        CurrentModelNode = null,
                        Model = null,
                        EventType = ModelEventType.OnProvisioned,
                        Object = currentApplications.FirstOrDefault(),
                        ObjectType = typeof(AppInstance),
                        ObjectDefinition = appModel,
                        ModelHost = modelHost
                    });
                }
            }
        }