/// <summary> /// Processes the specified solution path. /// </summary> /// <param name="projectsViewModel">The projects view model.</param> /// <param name="applicationOptionsViewModel">The application options view model.</param> /// <param name="ninjaCoderOptionsViewModel">The ninja coder options view model.</param> /// <param name="applicationSamplesOptionsViewModel">The application samples options view model.</param> /// <param name="viewsViewModel">The views view model.</param> /// <param name="pluginsViewModel">The plugins view model.</param> /// <param name="nugetPackagesViewModel">The nuget packages view model.</param> /// <param name="xamarinFormsLabsViewModel">The xamarin forms labs view model.</param> internal void Process( ProjectsViewModel projectsViewModel, ApplicationOptionsViewModel applicationOptionsViewModel, NinjaCoderOptionsViewModel ninjaCoderOptionsViewModel, ApplicationSamplesOptionsViewModel applicationSamplesOptionsViewModel, ViewsViewModel viewsViewModel, PluginsViewModel pluginsViewModel, NugetPackagesViewModel nugetPackagesViewModel, XamarinFormsLabsViewModel xamarinFormsLabsViewModel) { TraceService.WriteLine("ProjectsController::Process"); foreach (SelectableItemViewModel <ProjectTemplateInfo> projectTemplateInfo in projectsViewModel.Projects) { TraceService.WriteLine(projectTemplateInfo.Item.Name + " project selected=" + projectTemplateInfo.IsSelected); } this.VisualStudioService.WriteStatusBarMessage(NinjaMessages.NinjaIsRunning); this.applicationService.SuspendResharperIfRequested(); this.projectsService.IsNewSolution = this.VisualStudioService.SolutionAlreadyCreated; //// create the solution if we don't have one! if (this.projectsService.IsNewSolution == false) { this.VisualStudioService.SolutionService.CreateEmptySolution(projectsViewModel.GetSolutionPath(), projectsViewModel.Project); } if (this.SettingsService.CreateTestProjectsSolutionFolder) { this.VisualStudioService.SolutionService.AddSolutionFolder(this.SettingsService.TestProjectsSolutionFolderName); this.VisualStudioService.DTEService.SaveAll(); } this.messages = this.projectsService.AddProjects( this.VisualStudioService, projectsViewModel.GetSolutionPath(), projectsViewModel.GetFormattedRequiredTemplates()) .ToList(); this.projectsService.SetStartUpProject(); //// there is a bug in the xamarin iOS code that means it doesnt apply a couple of xml elements //// in the info.plist - here we fix that issue. if (this.SettingsService.FixInfoPlist) { this.applicationService.FixInfoPList(projectsViewModel.GetFormattedRequiredTemplates() .FirstOrDefault(x => x.ProjectSuffix == this.SettingsService.iOSProjectSuffix)); } IEnumerable <string> viewNugetCommands = new List <string>(); if (this.SettingsService.FrameworkType != FrameworkType.NoFramework && viewsViewModel != null) { //// if we dont have a viewmodel and view in memory - add one //// user will have dont show views and viewmodel options selected. if (!viewsViewModel.Views.Any()) { viewsViewModel.Add(); } IEnumerable <string> viewModelMessages = this.viewModelViewsService.AddViewModelsAndViews(viewsViewModel.Views); this.messages.AddRange(viewModelMessages); viewNugetCommands = this.viewModelViewsService.GetNugetCommands(); } TraceService.WriteLine("ProjectsController::Process GetApplication Commands"); //// we need to get the post nuget commands that are now hosted in xml file that used to be in code CommandsList commandsList = this.applicationService.GetCommandsList(); if (commandsList != null) { this.postNugetCommands.AddRange(commandsList.Commands); this.postNugetFileOperations.AddRange(commandsList.FileOperations); } IEnumerable <ProjectTemplateInfo> projectTemplateInfos = projectsViewModel.GetFormattedRequiredTemplates(); this.commands += this.nugetService.GetNugetCommands(projectTemplateInfos); if (viewNugetCommands.Any()) { foreach (string viewNugetCommand in viewNugetCommands) { this.commands += viewNugetCommand + Environment.NewLine; } } this.PopulateNugetActions(applicationOptionsViewModel); this.PopulateNugetActions(ninjaCoderOptionsViewModel); this.PopulateNugetActions(applicationSamplesOptionsViewModel); this.PopulateNugetActions(pluginsViewModel); this.PopulateNugetActions(nugetPackagesViewModel); this.PopulateNugetActions(xamarinFormsLabsViewModel); this.cachingService.PostNugetCommands = this.postNugetCommands; this.cachingService.PostNugetFileOperations = this.postNugetFileOperations; //// a bit of (unnecessary) tidying up - replace double new lines! this.commands = this.commands.Replace(Environment.NewLine + Environment.NewLine, Environment.NewLine); this.CreateReadMe(false, false); TraceService.WriteHeader("RequestedNugetCommands=" + this.commands); if (this.SettingsService.ProcessNugetCommands) { this.ProcessNugetCommands(); } TraceService.WriteLine("ProjectsController::Process END"); }
protected void ProcessView(object modelHost, SPList targetList, ListViewDefinition listViewModel) { var currentView = FindView(targetList, listViewModel); InvokeOnModelEvent(this, new ModelEventArgs { CurrentModelNode = null, Model = null, EventType = ModelEventType.OnProvisioning, Object = currentView, ObjectType = typeof(SPView), ObjectDefinition = listViewModel, ModelHost = modelHost }); if (currentView == null) { TraceService.Information((int)LogEventId.ModelProvisionProcessingNewObject, "Processing new list view"); var viewFields = new StringCollection(); viewFields.AddRange(listViewModel.Fields.ToArray()); // TODO, handle personal view creation currentView = targetList.Views.Add( string.IsNullOrEmpty(listViewModel.Url) ? listViewModel.Title : GetSafeViewUrl(listViewModel.Url), viewFields, listViewModel.Query, (uint)listViewModel.RowLimit, listViewModel.IsPaged, listViewModel.IsDefault); currentView.Title = listViewModel.Title; } else { TraceService.Information((int)LogEventId.ModelProvisionProcessingExistingObject, "Processing existing list view"); } // viewModel.InvokeOnDeployingModelEvents<ListViewDefinition, SPView>(currentView); // if any fields specified, overwrite if (listViewModel.Fields.Any()) { currentView.ViewFields.DeleteAll(); foreach (var viewField in listViewModel.Fields) { currentView.ViewFields.Add(viewField); } } currentView.Hidden = listViewModel.Hidden; currentView.Title = listViewModel.Title; currentView.RowLimit = (uint)listViewModel.RowLimit; currentView.DefaultView = listViewModel.IsDefault; currentView.Paged = listViewModel.IsPaged; #if !NET35 if (!string.IsNullOrEmpty(listViewModel.JSLink)) { currentView.JSLink = listViewModel.JSLink; } #endif if (!string.IsNullOrEmpty(listViewModel.Query)) { currentView.Query = listViewModel.Query; } if (listViewModel.DefaultViewForContentType.HasValue) { currentView.DefaultViewForContentType = listViewModel.DefaultViewForContentType.Value; } if (!string.IsNullOrEmpty(listViewModel.ContentTypeName)) { currentView.ContentTypeId = LookupListContentTypeByName(targetList, listViewModel.ContentTypeName); } if (!string.IsNullOrEmpty(listViewModel.ContentTypeId)) { currentView.ContentTypeId = LookupListContentTypeById(targetList, listViewModel.ContentTypeId); } // viewModel.InvokeOnModelUpdatedEvents<ListViewDefinition, SPView>(currentView); InvokeOnModelEvent(this, new ModelEventArgs { CurrentModelNode = null, Model = null, EventType = ModelEventType.OnProvisioned, Object = currentView, ObjectType = typeof(SPView), ObjectDefinition = listViewModel, ModelHost = modelHost }); TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "Calling currentView.Update()"); currentView.Update(); }
public override void DeployModel(object modelHost, DefinitionBase model) { var siteModelHost = modelHost.WithAssertAndCast <SiteModelHost>("modelHost", value => value.RequireNotNull()); var site = siteModelHost.HostSite; var securityGroupModel = model.WithAssertAndCast <SecurityGroupDefinition>("model", value => value.RequireNotNull()); var web = site.RootWeb; //var site = web.Site; var currentGroup = (SPGroup)null; var hasInitialGroup = false; try { currentGroup = site.RootWeb.SiteGroups[securityGroupModel.Name]; hasInitialGroup = true; TraceService.Information((int)LogEventId.ModelProvisionProcessingExistingObject, "Processing existing security group"); } catch (SPException) { var ownerUser = EnsureOwnerUser(web, securityGroupModel); var defaultUser = EnsureDefaultUser(web, securityGroupModel); TraceService.Information((int)LogEventId.ModelProvisionProcessingNewObject, "Processing new security group"); web.SiteGroups.Add(securityGroupModel.Name, ownerUser, defaultUser, securityGroupModel.Description); currentGroup = web.SiteGroups[securityGroupModel.Name]; } if (hasInitialGroup) { InvokeOnModelEvent(this, new ModelEventArgs { CurrentModelNode = null, Model = null, EventType = ModelEventType.OnProvisioning, Object = currentGroup, ObjectType = typeof(SPGroup), ObjectDefinition = securityGroupModel, ModelHost = modelHost }); } else { InvokeOnModelEvent(this, new ModelEventArgs { CurrentModelNode = null, Model = null, EventType = ModelEventType.OnProvisioning, Object = null, ObjectType = typeof(SPGroup), ObjectDefinition = securityGroupModel, ModelHost = modelHost }); } currentGroup.OnlyAllowMembersViewMembership = securityGroupModel.OnlyAllowMembersViewMembership; currentGroup.Owner = EnsureOwnerUser(web, securityGroupModel); currentGroup.Description = securityGroupModel.Description; InvokeOnModelEvent(this, new ModelEventArgs { CurrentModelNode = null, Model = null, EventType = ModelEventType.OnProvisioned, Object = currentGroup, ObjectType = typeof(SPGroup), ObjectDefinition = securityGroupModel, ModelHost = modelHost }); currentGroup.Update(); }
/// <summary> /// Gets the variables. /// </summary> /// <param name="instance">The instance.</param> /// <returns>The variables.</returns> public static IEnumerable <CodeVariable> GetVariables(this CodeClass instance) { TraceService.WriteLine("CodeClassExtensions::GetVariables file=" + instance.Name); return(instance.Members.OfType <CodeVariable>()); }
private void ProcessFeature( object modelHost, SPFeatureCollection features, FeatureDefinition featureModel) { var currentFeature = GetFeature(features, featureModel); var featureActivated = IsFeatureActivated(currentFeature); InvokeOnModelEvent(this, new ModelEventArgs { CurrentModelNode = null, Model = null, EventType = ModelEventType.OnProvisioning, Object = currentFeature, ObjectType = typeof(SPFeature), ObjectDefinition = featureModel, ModelHost = modelHost }); TraceService.VerboseFormat((int)LogEventId.ModelProvisionCoreCall, "Is feature activated: [{0}]", featureActivated); if (!featureActivated) { if (featureModel.Enable) { TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "Enabling feature"); var f = SafelyActivateFeature(features, featureModel); InvokeOnModelEvent(this, new ModelEventArgs { CurrentModelNode = null, Model = null, EventType = ModelEventType.OnProvisioned, Object = f, ObjectType = typeof(SPFeature), ObjectDefinition = featureModel, ModelHost = modelHost }); } else { InvokeOnModelEvent(this, new ModelEventArgs { CurrentModelNode = null, Model = null, EventType = ModelEventType.OnProvisioned, Object = currentFeature, ObjectType = typeof(SPFeature), ObjectDefinition = featureModel, ModelHost = modelHost }); } } else { if (featureModel.Enable && featureModel.ForceActivate) { TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "Feature enabled, but ForceActivate = true. Force activating."); var f = SafelyActivateFeature(features, featureModel); InvokeOnModelEvent(this, new ModelEventArgs { CurrentModelNode = null, Model = null, EventType = ModelEventType.OnProvisioned, Object = f, ObjectType = typeof(SPFeature), ObjectDefinition = featureModel, ModelHost = modelHost }); } else if (!featureModel.Enable) { TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "Removing feature."); features.Remove(featureModel.Id, featureModel.ForceActivate); InvokeOnModelEvent(this, new ModelEventArgs { CurrentModelNode = null, Model = null, EventType = ModelEventType.OnProvisioned, Object = null, ObjectType = typeof(SPFeature), ObjectDefinition = featureModel, ModelHost = modelHost }); } else { InvokeOnModelEvent(this, new ModelEventArgs { CurrentModelNode = null, Model = null, EventType = ModelEventType.OnProvisioned, Object = currentFeature, ObjectType = typeof(SPFeature), ObjectDefinition = featureModel, ModelHost = modelHost }); } } }
public override void Traverse(object modelHost, ModelNode modelNode) { try { var modelDefinition = modelNode.Value as DefinitionBase; var modelHandler = OnModelHandlerResolve(modelNode); TraceService.VerboseFormat((int)LogEventId.ModelProcessing, "Raising OnModelFullyProcessing for model: [{0}].", modelNode); if (OnModelFullyProcessing != null) { OnModelFullyProcessing(modelNode); } TraceService.VerboseFormat((int)LogEventId.ModelProcessing, "Raising OnModelProcessing for model: [{0}].", modelNode); if (OnModelProcessing != null) { OnModelProcessing(modelNode); } //var requireselfProcessing = modelDefinition.RequireSelfProcessing || modelNode.Options.RequireSelfProcessing; var requireselfProcessing = modelNode.Options.RequireSelfProcessing; TraceService.InformationFormat((int)LogEventId.ModelProcessing, "Deploying model [{0}] RSP: [{1}] : [{2}].", new[] { modelNode.Value.GetType().Name, requireselfProcessing.ToString(), modelNode.Value.ToString() }); if (requireselfProcessing) { try { modelHandler.DeployModel(modelHost, modelNode.Value); } catch (Exception e) { var onExceptionArgs = new ModelTreeTraverseServiceExceptionEventArgs { Handled = false, Exception = e }; if (OnException != null) { OnException(this, onExceptionArgs); } if (!onExceptionArgs.Handled) { throw; } } } TraceService.VerboseFormat((int)LogEventId.ModelProcessing, "Raising OnModelProcessed for model: [{0}].", modelNode); if (OnModelProcessed != null) { OnModelProcessed(modelNode); } var childModelTypes = GetSortedChildModelTypes(modelNode); foreach (var childModelType in childModelTypes) { TraceService.VerboseFormat((int)LogEventId.ModelProcessing, "Starting processing child models of type: [{0}].", new object[] { childModelType.Key }); var childModels = modelNode.GetChildModels(childModelType.Key).ToList(); ModelWeighService.SortChildModelNodes(modelNode, childModels); TraceService.VerboseFormat((int)LogEventId.ModelProcessing, "Found [{0}] models of type: [{1}].", new object[] { childModels.Count(), childModelType.Key }); TraceService.VerboseFormat((int)LogEventId.ModelProcessing, "Raising OnChildModelsProcessing of type: [{0}].", new object[] { childModelType.Key }); if (OnChildModelsProcessing != null) { OnChildModelsProcessing(modelNode, childModelType.Key, childModels); } foreach (var childModel in childModels) { TraceService.VerboseFormat((int)LogEventId.ModelProcessing, "Starting resolving model host of type: [{0}].", new object[] { childModelType.Key }); modelHandler.WithResolvingModelHost(new ModelHostResolveContext { ModelHost = modelHost, Model = modelDefinition, ChildModelType = childModelType.Key, ModelNode = modelNode, Action = childModelHost => { Traverse(childModelHost, childModel); } }); TraceService.VerboseFormat((int)LogEventId.ModelProcessing, "Finishing resolving model host of type: [{0}].", new object[] { childModelType.Key }); } TraceService.VerboseFormat((int)LogEventId.ModelProcessing, "Raising OnChildModelsProcessed of type: [{0}].", new object[] { childModelType.Key }); if (OnChildModelsProcessed != null) { OnChildModelsProcessed(modelNode, childModelType.Key, childModels); } TraceService.VerboseFormat((int)LogEventId.ModelProcessing, "Finishing processing child models of type: [{0}].", new object[] { childModelType.Key }); } TraceService.VerboseFormat((int)LogEventId.ModelProcessing, "Raising OnModelFullyProcessed for model: [{0}].", modelNode); if (OnModelFullyProcessed != null) { OnModelFullyProcessed(modelNode); } } catch (Exception e) { var onExceptionArgs = new ModelTreeTraverseServiceExceptionEventArgs { Handled = false, Exception = e }; if (OnException != null) { OnException(this, onExceptionArgs); } if (!onExceptionArgs.Handled) { if (e is SPMeta2ModelDeploymentException) { throw; } throw new SPMeta2ModelDeploymentException( "There was an error while provisioning definition. Check ModelNode prop.", e) { ModelNode = modelNode, }; } } }
private SPFile GetOrCreateNewWebPartFile(object modelHost, SPFolder folder, WebPartPageDefinition definition) { var list = folder.DocumentLibrary; var targetFile = FindWebPartPage(folder, definition); InvokeOnModelEvent(this, new ModelEventArgs { CurrentModelNode = null, Model = null, EventType = ModelEventType.OnProvisioning, Object = targetFile, ObjectType = typeof(SPFile), ObjectDefinition = definition, ModelHost = modelHost }); if (targetFile == null || definition.NeedOverride) { if (definition.NeedOverride) { TraceService.Information((int)LogEventId.ModelProvisionProcessingExistingObject, "Processing existing web part page"); TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "NeedOverride = true. Replacing web part page."); } else { TraceService.Information((int)LogEventId.ModelProvisionProcessingNewObject, "Processing new web part page"); } var webPartPageName = GetSafeWebPartPageFileName(definition); byte[] fileContent = null; if (!string.IsNullOrEmpty(definition.CustomPageLayout)) { fileContent = Encoding.UTF8.GetBytes(definition.CustomPageLayout); } else { fileContent = Encoding.UTF8.GetBytes(GetWebPartPageTemplateContent(definition)); } ModuleFileModelHandler.DeployModuleFile(folder, SPUrlUtility.CombineUrl(folder.ServerRelativeUrl, webPartPageName), webPartPageName, fileContent, true, file => { }, after => { FieldLookupService.EnsureDefaultValues(after.ListItemAllFields, definition.DefaultValues); if (!string.IsNullOrEmpty(definition.ContentTypeId) || !string.IsNullOrEmpty(definition.ContentTypeName)) { if (!string.IsNullOrEmpty(definition.ContentTypeId)) { after.ListItemAllFields["ContentTypeId"] = ContentTypeLookupService.LookupListContentTypeById(list, definition.ContentTypeId); } if (!string.IsNullOrEmpty(definition.ContentTypeName)) { after.ListItemAllFields["ContentTypeId"] = ContentTypeLookupService.LookupContentTypeByName(list, definition.ContentTypeName); } } FieldLookupService.EnsureValues(after.ListItemAllFields, definition.Values, true); if (definition.DefaultValues.Any() || definition.Values.Any() || !string.IsNullOrEmpty(definition.ContentTypeId) || !string.IsNullOrEmpty(definition.ContentTypeName)) { after.ListItemAllFields.Update(); } InvokeOnModelEvent(this, new ModelEventArgs { CurrentModelNode = null, Model = null, EventType = ModelEventType.OnProvisioned, Object = after, ObjectType = typeof(SPFile), ObjectDefinition = definition, ModelHost = modelHost }); }); targetFile = FindWebPartPage(folder, definition); } else { FieldLookupService.EnsureDefaultValues(targetFile.ListItemAllFields, definition.DefaultValues); if (!string.IsNullOrEmpty(definition.ContentTypeId) || !string.IsNullOrEmpty(definition.ContentTypeName)) { if (!string.IsNullOrEmpty(definition.ContentTypeId)) { targetFile.ListItemAllFields["ContentTypeId"] = ContentTypeLookupService.LookupListContentTypeById(list, definition.ContentTypeId); } if (!string.IsNullOrEmpty(definition.ContentTypeName)) { targetFile.ListItemAllFields["ContentTypeId"] = ContentTypeLookupService.LookupContentTypeByName(list, definition.ContentTypeName); } } TraceService.Information((int)LogEventId.ModelProvisionProcessingExistingObject, "Processing existing web part page"); TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "NeedOverride = false. Skipping replacing web part page."); InvokeOnModelEvent(this, new ModelEventArgs { CurrentModelNode = null, Model = null, EventType = ModelEventType.OnProvisioned, Object = targetFile, ObjectType = typeof(SPFile), ObjectDefinition = definition, ModelHost = modelHost }); targetFile.Update(); } return(targetFile); }
private void ProcessWebFolder(FolderModelHost folderHost, ModuleFileDefinition moduleFile) { var web = folderHost.HostWeb; var folder = folderHost.CurrentWebFolder; var context = web.Context; if (!folder.IsPropertyAvailable("ServerRelativeUrl")) { context.Load(folder, f => f.ServerRelativeUrl); context.ExecuteQueryWithTrace(); } var currentFile = web.GetFileByServerRelativeUrl(GetSafeFileUrl(folder, moduleFile)); context.Load(currentFile, f => f.Exists); context.ExecuteQuery(); InvokeOnModelEvent(this, new ModelEventArgs { CurrentModelNode = null, Model = null, EventType = ModelEventType.OnProvisioning, Object = currentFile.Exists ? currentFile : null, ObjectType = typeof(File), ObjectDefinition = moduleFile, ModelHost = folderHost }); if (moduleFile.Overwrite) { var fileCreatingInfo = new FileCreationInformation { Url = moduleFile.FileName, Overwrite = true }; if (moduleFile.Content.Length < ContentStreamFileSize) { TraceService.VerboseFormat((int)LogEventId.ModelProvisionCoreCall, "Using fileCreatingInfo.Content for small file less than: [{0}]", ContentStreamFileSize); fileCreatingInfo.Content = moduleFile.Content; } else { TraceService.VerboseFormat((int)LogEventId.ModelProvisionCoreCall, "Using fileCreatingInfo.ContentStream for big file more than: [{0}]", ContentStreamFileSize); fileCreatingInfo.ContentStream = new System.IO.MemoryStream(moduleFile.Content); } var file = folder.Files.Add(fileCreatingInfo); folder.Context.ExecuteQuery(); InvokeOnModelEvent(this, new ModelEventArgs { CurrentModelNode = null, Model = null, EventType = ModelEventType.OnProvisioned, Object = file, ObjectType = typeof(File), ObjectDefinition = moduleFile, ModelHost = folderHost }); } else { InvokeOnModelEvent(this, new ModelEventArgs { CurrentModelNode = null, Model = null, EventType = ModelEventType.OnProvisioned, Object = currentFile.Exists ? currentFile : null, ObjectType = typeof(File), ObjectDefinition = moduleFile, ModelHost = folderHost }); } folder.Update(); folder.Context.ExecuteQueryWithTrace(); }
protected virtual void ProcessGenericLocalization(ClientObject obj, Dictionary <string, List <ValueForUICulture> > localizations) { var targetProps = localizations.Keys.ToList(); var isSupportedRuntime = ReflectionUtils.HasProperties(obj, targetProps); if (!isSupportedRuntime) { TraceService.Critical((int)LogEventId.ModelProvisionCoreCall, string.Format("CSOM runtime doesn't have [{0}] methods support. Update CSOM runtime to a new version. Provision is skipped", string.Join(", ", targetProps.ToArray()))); return; } var needsUpdate = false; foreach (var key in localizations.Keys) { var propName = key; var localization = localizations[key]; if (localization.Any()) { var userResource = GetPropertyValue(obj, propName); foreach (var locValue in localization) { LocalizationService.ProcessUserResource(obj, userResource, locValue); } needsUpdate = true; } } if (needsUpdate) { var updateMethod = ReflectionUtils.GetMethod(obj, "Update"); if (updateMethod != null) { if (obj is ContentType) { updateMethod.Invoke(obj, new object[] { true }); } else if (obj is Field) { updateMethod = ReflectionUtils.GetMethod(obj, "UpdateAndPushChanges"); updateMethod.Invoke(obj, new object[] { true }); } else { updateMethod.Invoke(obj, null); } obj.Context.ExecuteQueryWithTrace(); } else { throw new SPMeta2Exception(String.Format("Can't find Update() methods on client object of type:[{0}]", obj.GetType())); } } }
/// <summary> /// Adds the text template to projects. /// </summary> /// <param name="instance">The instance.</param> /// <param name="textTemplateInfos">The text template infos.</param> /// <param name="outputTextTemplateContentToTraceFile">if set to <c>true</c> [output text template content to trace file].</param> /// <returns></returns> public static IEnumerable <string> AddTextTemplateToProjects( this Solution2 instance, IEnumerable <TextTemplateInfo> textTemplateInfos, bool outputTextTemplateContentToTraceFile) { string method = "SolutionExtensions::AddTextTemplateToProjects "; TraceService.WriteLine(method); List <string> messages = new List <string>(); IEnumerable <Project> projects = instance.GetProjects(); IEnumerable <Project> projectItems = projects as Project[] ?? projects.ToArray(); foreach (TextTemplateInfo info in textTemplateInfos) { Project project = projectItems.FirstOrDefault(x => x.Name.EndsWith(info.ProjectSuffix)); if (project != null) { string context = project.Name + " (template=" + info.ShortTemplateName + ") fileName=" + info.FileName; TraceService.WriteLine(method + context); try { instance.DTE.StatusBar.Text = "Adding Text Template to project " + project.Name; if (project.AddTextTemplate(info.ProjectFolder, info.FileName, info.TextOutput, outputTextTemplateContentToTraceFile) != string.Empty) { messages.Add(info.FileName + " added to " + project.Name + " project (template=" + info.ShortTemplateName + ")"); } if (info.ChildItems != null) { foreach (TextTemplateInfo childItem in info.ChildItems) { TraceService.WriteLine("Adding child Text Template projectFolder=" + childItem.ProjectFolder + " fileName=" + childItem.FileName); try { project.AddTextTemplate( childItem.ProjectFolder, childItem.FileName, childItem.TextOutput, outputTextTemplateContentToTraceFile); } catch (Exception exception) { TraceService.WriteError(method + " Adding child Text Template exception=" + exception.Message); messages.Add(method + " Adding child Text Template exception=" + exception.Message); } } } } catch (Exception exception) { TraceService.WriteError(method + context + " exception=" + exception.Message); messages.Add(method + context + " exception=" + exception.Message); } } else { TraceService.WriteError(method + " cannot find project " + info.ProjectSuffix); foreach (string projectName in projectItems .Select(projectItem => projectItem.Name)) { TraceService.WriteError(method + " project " + projectName); messages.Add(info.FileName + " added to " + projectName + " project (template=" + info.ShortTemplateName + ")"); } } } return(messages); }
private File ProcessFile(FolderModelHost folderHost, ModuleFileDefinition moduleFile) { var context = folderHost.CurrentLibraryFolder.Context; var web = folderHost.CurrentWeb; var list = folderHost.CurrentList; var folder = folderHost.CurrentLibraryFolder; context.Load(folder, f => f.ServerRelativeUrl); context.ExecuteQueryWithTrace(); var stringCustomContentType = ResolveContentTypeId(folderHost, moduleFile); if (list != null) { context.Load(list, l => l.EnableMinorVersions); context.Load(list, l => l.EnableVersioning); context.Load(list, l => l.EnableModeration); context.ExecuteQueryWithTrace(); } var file = web.GetFileByServerRelativeUrl(GetSafeFileUrl(folder, moduleFile)); context.Load(file, f => f.Exists); context.ExecuteQueryWithTrace(); InvokeOnModelEvent <ModuleFileDefinition, File>(file, ModelEventType.OnUpdating); InvokeOnModelEvent(this, new ModelEventArgs { CurrentModelNode = null, Model = null, EventType = ModelEventType.OnProvisioning, Object = file.Exists ? file : null, ObjectType = typeof(File), ObjectDefinition = moduleFile, ModelHost = folderHost }); WithSafeFileOperation(list, file, f => { var fileName = moduleFile.FileName; var fileContent = moduleFile.Content; var fileCreatingInfo = new FileCreationInformation { Url = fileName, Overwrite = file.Exists }; if (fileContent.Length < ContentStreamFileSize) { TraceService.VerboseFormat((int)LogEventId.ModelProvisionCoreCall, "Using fileCreatingInfo.Content for small file less than: [{0}]", ContentStreamFileSize); fileCreatingInfo.Content = fileContent; } else { TraceService.VerboseFormat((int)LogEventId.ModelProvisionCoreCall, "Using fileCreatingInfo.ContentStream for big file more than: [{0}]", ContentStreamFileSize); fileCreatingInfo.ContentStream = new System.IO.MemoryStream(fileContent); } TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "Overwriting file"); var updatedFile = folder.Files.Add(fileCreatingInfo); var newFileItem = updatedFile.ListItemAllFields; //context.Load(newFileItem); //context.ExecuteQueryWithTrace(); if (!string.IsNullOrEmpty(stringCustomContentType)) { newFileItem[BuiltInInternalFieldNames.ContentTypeId] = stringCustomContentType; } if (moduleFile.DefaultValues.Count > 0) { EnsureDefaultValues(newFileItem, moduleFile); } if (!string.IsNullOrEmpty(stringCustomContentType) || moduleFile.DefaultValues.Count > 0) { newFileItem.Update(); } return(updatedFile); }); var resultFile = web.GetFileByServerRelativeUrl(GetSafeFileUrl(folder, moduleFile)); context.Load(resultFile, f => f.Exists); context.ExecuteQueryWithTrace(); InvokeOnModelEvent(this, new ModelEventArgs { CurrentModelNode = null, Model = null, EventType = ModelEventType.OnProvisioned, Object = resultFile, ObjectType = typeof(File), ObjectDefinition = moduleFile, ModelHost = folderHost }); InvokeOnModelEvent <ModuleFileDefinition, File>(resultFile, ModelEventType.OnUpdated); return(resultFile); }
public override void DeployModel(object modelHost, DefinitionBase model) { var folderModelHost = modelHost as FolderModelHost; var webPartPageModel = model as WebPartPageDefinition; Folder folder = folderModelHost.CurrentLibraryFolder; //if (!string.IsNullOrEmpty(webPartPageModel.FolderUrl)) // throw new NotImplementedException("FolderUrl for the web part page model is not supported yet"); var context = folder.Context; // #SPBug // it turns out that there is no support for the web part page creating via CMOM // we we need to get a byte array to 'hack' this pages out.. // http://stackoverflow.com/questions/6199990/creating-a-sharepoint-2010-page-via-the-client-object-model // http://social.technet.microsoft.com/forums/en-US/sharepointgeneralprevious/thread/6565bac1-daf0-4215-96b2-c3b64270ec08 var currentPage = GetCurrentWebPartPage(folderModelHost.CurrentList, folder, GetSafeWebPartPageFileName(webPartPageModel)); InvokeOnModelEvent(this, new ModelEventArgs { CurrentModelNode = null, Model = null, EventType = ModelEventType.OnProvisioning, Object = currentPage, ObjectType = typeof(File), ObjectDefinition = webPartPageModel, ModelHost = modelHost }); if ((currentPage == null) || (currentPage != null && webPartPageModel.NeedOverride)) { if (webPartPageModel.NeedOverride) { TraceService.Information((int)LogEventId.ModelProvisionProcessingExistingObject, "Processing existing web part page"); TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "NeedOverride = true. Replacing web part page."); } else { TraceService.Information((int)LogEventId.ModelProvisionProcessingNewObject, "Processing new web part page"); } var file = new FileCreationInformation(); var pageContent = string.Empty; if (!string.IsNullOrEmpty(webPartPageModel.CustomPageLayout)) { pageContent = webPartPageModel.CustomPageLayout; } else { pageContent = GetWebPartTemplateContent(webPartPageModel); } var fileName = GetSafeWebPartPageFileName(webPartPageModel); file.Url = fileName; file.Content = Encoding.UTF8.GetBytes(pageContent); file.Overwrite = webPartPageModel.NeedOverride; var newFile = folder.Files.Add(file); InvokeOnModelEvent(this, new ModelEventArgs { CurrentModelNode = null, Model = null, EventType = ModelEventType.OnProvisioned, Object = newFile, ObjectType = typeof(File), ObjectDefinition = webPartPageModel, ModelHost = modelHost }); context.Load(newFile); context.ExecuteQueryWithTrace(); } else { TraceService.Information((int)LogEventId.ModelProvisionProcessingExistingObject, "Processing existing web part page"); TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "NeedOverride = false. Skipping replacing web part page."); InvokeOnModelEvent(this, new ModelEventArgs { CurrentModelNode = null, Model = null, EventType = ModelEventType.OnProvisioned, Object = currentPage, ObjectType = typeof(File), ObjectDefinition = webPartPageModel, ModelHost = modelHost }); } }
public override void WithResolvingModelHost(ModelHostResolveContext modelHostContext) { var modelHost = modelHostContext.ModelHost; var model = modelHostContext.Model; var childModelType = modelHostContext.ChildModelType; var action = modelHostContext.Action; var site = ExtractSite(modelHost); var web = ExtractWeb(modelHost); var mdHHost = modelHost as CSOMModelHostBase; var contentTypeModel = model as ContentTypeDefinition; if (web != null && contentTypeModel != null) { var context = web.Context; var id = contentTypeModel.GetContentTypeId(); var currentContentType = web.ContentTypes.GetById(id); context.ExecuteQueryWithTrace(); if (childModelType == typeof(ModuleFileDefinition)) { TraceService.Information((int)LogEventId.ModelProvisionCoreCall, "Resolving content type resource folder for ModuleFileDefinition"); var serverRelativeFolderUrl = ExtractResourceFolderServerRelativeUrl(web, context, currentContentType); var ctFolder = web.GetFolderByServerRelativeUrl(serverRelativeFolderUrl); context.ExecuteQueryWithTrace(); var folderModelHost = ModelHostBase.Inherit <FolderModelHost>(mdHHost, host => { host.CurrentContentType = currentContentType; host.CurrentContentTypeFolder = ctFolder; }); action(folderModelHost); } else { action(new ModelHostContext { Site = site, Web = web, ContentType = currentContentType }); } TraceService.Information((int)LogEventId.ModelProvisionCoreCall, "Calling currentContentType.Update(true)"); currentContentType.Update(true); context.ExecuteQueryWithTrace(); } else { action(modelHost); } }
public override void DeployModel(object modelHost, DefinitionBase model) { var site = ExtractSite(modelHost); var web = ExtractWeb(modelHost); var contentTypeModel = model.WithAssertAndCast <ContentTypeDefinition>("model", value => value.RequireNotNull()); var context = web.Context; var contentTypeId = contentTypeModel.GetContentTypeId(); var tmpContentType = context.LoadQuery(web.ContentTypes.Where(ct => ct.StringId == contentTypeId)); context.ExecuteQueryWithTrace(); var tmp = tmpContentType.FirstOrDefault(); InvokeOnModelEvent(this, new ModelEventArgs { CurrentModelNode = null, Model = null, EventType = ModelEventType.OnProvisioning, Object = tmp, ObjectType = typeof(ContentType), ObjectDefinition = model, ModelHost = modelHost }); InvokeOnModelEvent <ContentTypeDefinition, ContentType>(null, ModelEventType.OnUpdating); ContentType currentContentType = null; if (tmp == null || tmp.ServerObjectIsNull == null || tmp.ServerObjectIsNull.Value) { TraceService.Information((int)LogEventId.ModelProvisionProcessingNewObject, "Processing new content type"); currentContentType = web.ContentTypes.Add(new ContentTypeCreationInformation { Name = contentTypeModel.Name, Description = string.IsNullOrEmpty(contentTypeModel.Description) ? string.Empty : contentTypeModel.Description, Group = contentTypeModel.Group, Id = contentTypeId, ParentContentType = null }); } else { TraceService.Information((int)LogEventId.ModelProvisionProcessingExistingObject, "Processing existing content type"); currentContentType = tmp; } currentContentType.Hidden = contentTypeModel.Hidden; currentContentType.Name = contentTypeModel.Name; currentContentType.Description = string.IsNullOrEmpty(contentTypeModel.Description) ? string.Empty : contentTypeModel.Description; currentContentType.Group = contentTypeModel.Group; if (!string.IsNullOrEmpty(contentTypeModel.DocumentTemplate)) { var serverRelativeFolderUrl = ExtractResourceFolderServerRelativeUrl(web, context, currentContentType); var processedDocumentTemplateUrl = TokenReplacementService.ReplaceTokens(new TokenReplacementContext { Value = contentTypeModel.DocumentTemplate, Context = context }).Value; // resource related path if (!processedDocumentTemplateUrl.Contains('/') && !processedDocumentTemplateUrl.Contains('\\')) { processedDocumentTemplateUrl = UrlUtility.CombineUrl(new string[] { serverRelativeFolderUrl, processedDocumentTemplateUrl }); } currentContentType.DocumentTemplate = processedDocumentTemplateUrl; } InvokeOnModelEvent <ContentTypeDefinition, ContentType>(currentContentType, ModelEventType.OnUpdated); InvokeOnModelEvent(this, new ModelEventArgs { CurrentModelNode = null, Model = null, EventType = ModelEventType.OnProvisioned, Object = currentContentType, ObjectType = typeof(ContentType), ObjectDefinition = model, ModelHost = modelHost }); TraceService.Information((int)LogEventId.ModelProvisionCoreCall, "Calling currentContentType.Update(true)"); currentContentType.Update(true); context.ExecuteQueryWithTrace(); }
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(SPAppInstance), ObjectDefinition = appModel, ModelHost = modelHost }); if (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); if (newAppInstance != null && newAppInstance.Status == SPAppInstanceStatus.Initialized) { appId = newAppInstance.Id; var count = 0; SPAppInstance 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); count++; } while (localInstance != null && localInstance.Status != SPAppInstanceStatus.Installed && count < MaxInstallAttempCount); } newAppInstance = web.GetAppInstanceById(appId); InvokeOnModelEvent(this, new ModelEventArgs { CurrentModelNode = null, Model = null, EventType = ModelEventType.OnProvisioned, Object = newAppInstance, ObjectType = typeof(SPAppInstance), 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.App.VersionString, 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); if (definitionVersion > spAppVersion) { TraceService.Information((int)LogEventId.ModelProvisionProcessingExistingObject, "Performing upgrade"); var updateAppInstance = currentApplications[i]; var updateAppId = updateAppInstance.Id; var count = 0; SPAppInstance localUpdateAppInstance = null; updateAppInstance.Upgrade(appPackage); do { TraceService.VerboseFormat((int)LogEventId.ModelProvisionCoreCall, "Waiting while app is being installed for [{0}] milliseconds.", WaitTimeInMillliseconds); Thread.Sleep(WaitTimeInMillliseconds); localUpdateAppInstance = web.GetAppInstanceById(updateAppId); count++; } while (localUpdateAppInstance != null && localUpdateAppInstance.Status != SPAppInstanceStatus.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); } InvokeOnModelEvent(this, new ModelEventArgs { CurrentModelNode = null, Model = null, EventType = ModelEventType.OnProvisioned, Object = currentApplications.FirstOrDefault(), ObjectType = typeof(SPAppInstance), ObjectDefinition = appModel, ModelHost = modelHost }); } } }
/// <summary> /// Adds the projects. /// </summary> /// <param name="instance">The instance.</param> /// <param name="path">The path.</param> /// <param name="projectsInfos">The projects infos.</param> /// <param name="referenceFirstProject">if set to <c>true</c> [reference first project].</param> public static void AddProjects( this Solution2 instance, string path, IEnumerable <ProjectTemplateInfo> projectsInfos, bool referenceFirstProject) { string message = string.Format( "SolutionExtensions::AddProjects project count={0} path={1}", projectsInfos.Count(), path); TraceService.WriteLine(message); Project firstProject = null; Solution solution = instance as Solution; foreach (ProjectTemplateInfo projectInfo in projectsInfos) { try { //// Project may actually already exist - if so just skip it! if (Directory.Exists(path + "\\" + projectInfo.Name) == false) { try { string template = instance.GetProjectTemplate(projectInfo.TemplateName); solution.AddProjectToSolution(path, template, projectInfo.Name); } catch (Exception exception) { string exceptionMessage = string.Format( "Unsupported project {0} not added to the solution.", projectInfo.Name); TraceService.WriteError(exceptionMessage + " exception=" + exception.Message); MessageBox.Show(exceptionMessage, "Scorchio.VisualStudio"); } } if (referenceFirstProject) { Project project = instance.GetProject(projectInfo.Name); if (project != null) { if (firstProject == null) { firstProject = project; } else { try { project.AddProjectReference(firstProject); } catch (Exception exception) { TraceService.WriteLine("SolutionExtensions::AddProjects Error=" + exception.Message); } } } } } catch (FileNotFoundException exception) { //// if template not found just miss it out for now. message = string.Format( "Template not found for {0} Error {1}", projectInfo.TemplateName, exception.Message); TraceService.WriteError(message); } } }
public override void DeployModel(object modelHost, DefinitionBase model) { var listMOdelHost = modelHost.WithAssertAndCast <ListModelHost>("modelHost", value => value.RequireNotNull()); var listViewModel = model.WithAssertAndCast <ListViewDefinition>("model", value => value.RequireNotNull()); var list = listMOdelHost.HostList; var currentView = FindView(list, listViewModel); InvokeOnModelEvent(this, new ModelEventArgs { CurrentModelNode = null, Model = null, EventType = ModelEventType.OnProvisioning, Object = currentView, ObjectType = typeof(View), ObjectDefinition = listViewModel, ModelHost = modelHost }); if (currentView == null) { TraceService.Information((int)LogEventId.ModelProvisionProcessingNewObject, "Processing new list view"); var newView = new ViewCreationInformation { Title = string.IsNullOrEmpty(listViewModel.Url) ? listViewModel.Title : GetSafeViewUrl(listViewModel.Url), RowLimit = (uint)listViewModel.RowLimit, SetAsDefaultView = listViewModel.IsDefault, Paged = listViewModel.IsPaged }; if (!string.IsNullOrEmpty(listViewModel.Query)) { newView.Query = listViewModel.Query; } if (listViewModel.Fields != null && listViewModel.Fields.Any()) { newView.ViewFields = listViewModel.Fields.ToArray(); } if (!string.IsNullOrEmpty(listViewModel.Type)) { newView.ViewTypeKind = (ViewType)Enum.Parse(typeof(ViewType), string.IsNullOrEmpty(listViewModel.Type) ? BuiltInViewType.Html : listViewModel.Type); } currentView = list.Views.Add(newView); MapListViewProperties(list, currentView, listViewModel); currentView.Update(); list.Context.ExecuteQueryWithTrace(); currentView = FindView(list, listViewModel); list.Context.Load(currentView); list.Context.ExecuteQueryWithTrace(); } else { list.Context.Load(currentView); list.Context.ExecuteQueryWithTrace(); TraceService.Information((int)LogEventId.ModelProvisionProcessingExistingObject, "Processing existing list view"); MapListViewProperties(list, currentView, listViewModel); } ProcessLocalization(currentView, listViewModel); InvokeOnModelEvent(this, new ModelEventArgs { CurrentModelNode = null, Model = null, EventType = ModelEventType.OnProvisioned, Object = currentView, ObjectType = typeof(View), ObjectDefinition = listViewModel, ModelHost = modelHost }); TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "Calling currentView.Update()"); currentView.Update(); list.Context.ExecuteQueryWithTrace(); }
public override void DeployModel(object modelHost, DefinitionBase model) { var securableObject = ExtractSecurableObject(modelHost); var securityGroupLinkModel = model.WithAssertAndCast <SecurityGroupLinkDefinition>("model", value => value.RequireNotNull()); var web = GetWebFromSPSecurableObject(securableObject); var context = web.Context; context.Load(web, w => w.SiteGroups); context.Load(web, w => w.RoleDefinitions); context.Load(securableObject, s => s.HasUniqueRoleAssignments); context.Load(securableObject, s => s.RoleAssignments.Include(r => r.Member)); context.ExecuteQueryWithTrace(); Group securityGroup = ResolveSecurityGroup(securityGroupLinkModel, web, context); if (!securableObject.HasUniqueRoleAssignments) { TraceService.Information((int)LogEventId.ModelProvisionCoreCall, "securableObject.HasUniqueRoleAssignments = false. Breaking with false-false options."); securableObject.BreakRoleInheritance(false, false); } var roleAssignment = FindRoleRoleAssignment(securableObject.RoleAssignments, securityGroup); InvokeOnModelEvent(this, new ModelEventArgs { CurrentModelNode = null, Model = null, EventType = ModelEventType.OnProvisioning, Object = roleAssignment, ObjectType = typeof(RoleAssignment), ObjectDefinition = securityGroupLinkModel, ModelHost = modelHost }); if (roleAssignment == null) { TraceService.Information((int)LogEventId.ModelProvisionProcessingNewObject, "Processing new security group link"); // add default guest role as hidden one // we need to at least one role in order to create assignment // further provision will chech of there is only one role - Reader, and will remove it var bindings = new RoleDefinitionBindingCollection(context); bindings.Add(web.RoleDefinitions.GetByType(RoleType.Reader)); var assegnment = securableObject.RoleAssignments.Add(securityGroup, bindings); InvokeOnModelEvent(this, new ModelEventArgs { CurrentModelNode = null, Model = null, EventType = ModelEventType.OnProvisioned, Object = assegnment, ObjectType = typeof(RoleAssignment), ObjectDefinition = securityGroupLinkModel, ModelHost = modelHost }); context.ExecuteQuery(); } else { TraceService.Information((int)LogEventId.ModelProvisionProcessingExistingObject, "Processing existing security group link"); InvokeOnModelEvent(this, new ModelEventArgs { CurrentModelNode = null, Model = null, EventType = ModelEventType.OnProvisioned, Object = roleAssignment, ObjectType = typeof(RoleAssignment), ObjectDefinition = securityGroupLinkModel, ModelHost = modelHost }); } }
public override void DeployModel(object modelHost, DefinitionBase model) { var listModelHost = modelHost.WithAssertAndCast <ListModelHost>("modelHost", value => value.RequireNotNull()); var definition = model.WithAssertAndCast <ListViewDefinition>("model", value => value.RequireNotNull()); var list = listModelHost.HostList; var context = list.Context; context.Load(list, l => l.Fields); context.Load(list, l => l.Views.Include( v => v.ViewFields, v => v.Title, v => v.DefaultView, v => v.ViewQuery, v => v.RowLimit, v => v.Paged, v => v.Scope, v => v.Hidden, v => v.JSLink, v => v.ServerRelativeUrl, v => v.DefaultViewForContentType, v => v.ContentTypeId, v => v.AggregationsStatus, v => v.Aggregations, v => v.ViewType, v => v.IncludeRootFolder, v => v.HtmlSchemaXml, v => v.ViewData)); context.ExecuteQueryWithTrace(); var spObject = FindViewByTitle(list.Views, definition.Title); var assert = ServiceFactory.AssertService .NewAssert(definition, spObject); assert .ShouldNotBeNull(spObject) .ShouldBeEqual(m => m.Title, o => o.Title) .ShouldBeEqual(m => m.IsDefault, o => o.DefaultView) .ShouldBeEqual(m => m.Hidden, o => o.Hidden) .ShouldBeEqual(m => m.RowLimit, o => (int)o.RowLimit) .ShouldBeEqual(m => m.IsPaged, o => o.Paged); if (!string.IsNullOrEmpty(definition.Scope)) { assert.ShouldBeEqual((p, s, d) => { var srcProp = s.GetExpressionValue(def => def.Scope); var dstProp = d.GetExpressionValue(o => o.Scope); var scopeValue = ListViewScopeTypesConvertService.NormilizeValueToCSOMType(definition.Scope); var isValid = scopeValue == d.Scope.ToString(); return(new PropertyValidationResult { Tag = p.Tag, Src = srcProp, Dst = dstProp, IsValid = isValid }); }); } else { assert.SkipProperty(m => m.Scope); } if (!string.IsNullOrEmpty(definition.ViewData)) { assert.ShouldBeEqual((p, s, d) => { var srcProp = s.GetExpressionValue(def => def.ViewData); var dstProp = d.GetExpressionValue(o => o.ViewData); var srcViewDate = assert.Src.ViewData.Replace(System.Environment.NewLine, string.Empty).Replace(" /", "/"); var dstViewDate = assert.Dst.ViewData.Replace(System.Environment.NewLine, string.Empty).Replace(" /", "/"); // replacing all new lines srcViewDate = Regex.Replace(srcViewDate, @"\r\n?|\n", string.Empty); dstViewDate = Regex.Replace(dstViewDate, @"\r\n?|\n", string.Empty); var isValid = srcViewDate.ToUpper() == dstViewDate.ToUpper(); return(new PropertyValidationResult { Tag = p.Tag, Src = srcProp, Dst = dstProp, IsValid = isValid }); }); } else { assert.SkipProperty(m => m.ViewData); } if (definition.Types.Count() == 0) { assert.SkipProperty(m => m.Types, "Types.Count == 0"); if (!string.IsNullOrEmpty(definition.Type)) { assert.ShouldBeEqual((p, s, d) => { var srcProp = s.GetExpressionValue(def => def.Type); var dstProp = d.GetExpressionValue(o => o.ViewType); var isValid = srcProp.Value.ToString().ToUpper() == dstProp.Value.ToString().ToUpper(); return(new PropertyValidationResult { Tag = p.Tag, Src = srcProp, Dst = dstProp, IsValid = isValid }); }); } else { assert.SkipProperty(m => m.Type); } } else { assert.SkipProperty(m => m.Type, "Types.Count != 0"); assert.ShouldBeEqual((p, s, d) => { var srcProp = s.GetExpressionValue(def => def.Types); //var dstProp = d.GetExpressionValue(o => o.Type); var isValid = false; ViewType?srcType = null; foreach (var type in s.Types) { var tmpViewType = (ViewType)Enum.Parse(typeof(ViewType), type); if (srcType == null) { srcType = tmpViewType; } else { srcType = srcType | tmpViewType; } } var srcTypeValue = (int)srcType; var dstTypeValue = (int)0; // checking if only reccurence set // test designed that way only if (((int)srcTypeValue & (int)(ViewType.Recurrence)) == (int)ViewType.Recurrence) { // nah, whatever, it works and does the job isValid = d.HtmlSchemaXml.Contains("RecurrenceRowset=\"TRUE\""); } return(new PropertyValidationResult { Tag = p.Tag, Src = srcProp, Dst = null, IsValid = isValid }); }); } assert.SkipProperty(m => m.ViewStyleId, "ViewStyleId unsupported by SP CSOM API yet. Skipping."); assert.SkipProperty(m => m.TabularView, "TabularView unsupported by SP CSOM API yet. Skipping."); assert.SkipProperty(m => m.InlineEdit, "InlineEdit unsupported by SP CSOM API yet. Skipping."); assert.ShouldBeEqualIfNotNullOrEmpty(m => m.JSLink, o => o.JSLink); if (definition.IncludeRootFolder.HasValue) { assert.ShouldBeEqual(m => m.IncludeRootFolder, o => o.IncludeRootFolder); } else { assert.SkipProperty(m => m.IncludeRootFolder, "IncludeRootFolder is null or empty. Skipping."); } if (!string.IsNullOrEmpty(definition.Query)) { assert.ShouldBeEqual((p, s, d) => { var srcProp = s.GetExpressionValue(def => def.Query); var dstProp = d.GetExpressionValue(o => o.ViewQuery); var srcViewDate = assert.Src.Query.Replace(System.Environment.NewLine, string.Empty).Replace(" /", "/"); var dstViewDate = assert.Dst.ViewQuery.Replace(System.Environment.NewLine, string.Empty).Replace(" /", "/"); // replacing all new lines srcViewDate = Regex.Replace(srcViewDate, @"\r\n?|\n", string.Empty); dstViewDate = Regex.Replace(dstViewDate, @"\r\n?|\n", string.Empty); var isValid = srcViewDate.ToUpper() == dstViewDate.ToUpper(); return(new PropertyValidationResult { Tag = p.Tag, Src = srcProp, Dst = dstProp, IsValid = isValid }); }); } else { assert.SkipProperty(m => m.Query, "Query is null or empty. Skipping."); } assert.ShouldBeEqualIfHasValue(m => m.DefaultViewForContentType, o => o.DefaultViewForContentType); if (string.IsNullOrEmpty(definition.ContentTypeName)) { assert.SkipProperty(m => m.ContentTypeName, "ContentTypeName is null or empty. Skipping."); } else { var contentTypeId = LookupListContentTypeByName(list, definition.ContentTypeName); assert.ShouldBeEqual((p, s, d) => { var srcProp = s.GetExpressionValue(def => def.ContentTypeName); var dstProp = d.GetExpressionValue(ct => ct.ContentTypeId); var isValis = contentTypeId.StringValue == d.ContentTypeId.StringValue; return(new PropertyValidationResult { Tag = p.Tag, Src = srcProp, Dst = dstProp, IsValid = isValis }); }); } if (string.IsNullOrEmpty(definition.ContentTypeId)) { assert.SkipProperty(m => m.ContentTypeId, "ContentTypeId is null or empty. Skipping."); } else { var contentTypeId = LookupListContentTypeById(list, definition.ContentTypeId); assert.ShouldBeEqual((p, s, d) => { var srcProp = s.GetExpressionValue(def => def.ContentTypeId); var dstProp = d.GetExpressionValue(ct => ct.ContentTypeId); var isValis = contentTypeId.StringValue == d.ContentTypeId.StringValue; return(new PropertyValidationResult { Tag = p.Tag, Src = srcProp, Dst = dstProp, IsValid = isValis }); }); } if (string.IsNullOrEmpty(definition.AggregationsStatus)) { assert.SkipProperty(m => m.AggregationsStatus, "Aggregationsstatus is null or empty. Skipping."); } else { assert.ShouldBeEqual(m => m.AggregationsStatus, o => o.AggregationsStatus); } if (string.IsNullOrEmpty(definition.Aggregations)) { assert.SkipProperty(m => m.Aggregations, "Aggregations is null or empty. Skipping."); } else { assert.ShouldBeEqual((p, s, d) => { var srcProp = s.GetExpressionValue(def => def.Aggregations); var dstProp = d.GetExpressionValue(ct => ct.Aggregations); var isValid = s.Aggregations .Replace("'", string.Empty) .Replace(" ", string.Empty) .Replace("\"", string.Empty) == d.Aggregations .Replace("'", string.Empty) .Replace(" ", string.Empty) .Replace("\"", string.Empty); return(new PropertyValidationResult { Tag = p.Tag, Src = srcProp, Dst = dstProp, IsValid = isValid }); }); } assert.ShouldBePartOfIfNotNullOrEmpty(m => m.Url, o => o.ServerRelativeUrl); assert.ShouldBeEqual((p, s, d) => { var srcProp = s.GetExpressionValue(def => def.Fields); var dstProp = d.GetExpressionValue(ct => ct.ViewFields); var hasAllFields = true; foreach (var srcField in s.Fields) { var listField = list.Fields.ToList().FirstOrDefault(f => f.StaticName == srcField); // if list-scoped field we need to check by internal name // internal name is changed for list scoped-fields // that's why to check by BOTH, definition AND real internal name if (!d.ViewFields.ToList().Contains(srcField) && !d.ViewFields.ToList().Contains(listField.InternalName)) { hasAllFields = false; } } return(new PropertyValidationResult { Tag = p.Tag, Src = srcProp, Dst = dstProp, IsValid = hasAllFields }); }); var supportsLocalization = ReflectionUtils.HasProperties(spObject, new[] { "TitleResource" }); if (supportsLocalization) { if (definition.TitleResource.Any()) { assert.ShouldBeEqual((p, s, d) => { var srcProp = s.GetExpressionValue(def => def.TitleResource); var isValid = true; foreach (var userResource in s.TitleResource) { var culture = LocalizationService.GetUserResourceCultureInfo(userResource); var resourceObject = ReflectionUtils.GetPropertyValue(spObject, "TitleResource"); var value = ReflectionUtils.GetMethod(resourceObject, "GetValueForUICulture") .Invoke(resourceObject, new[] { culture.Name }) as ClientResult <string>; context.ExecuteQuery(); isValid = userResource.Value == value.Value; if (!isValid) { break; } } return(new PropertyValidationResult { Tag = p.Tag, Src = srcProp, Dst = null, IsValid = isValid }); }); } else { assert.SkipProperty(m => m.TitleResource, "TitleResource is NULL or empty. Skipping."); } } else { TraceService.Critical((int)LogEventId.ModelProvisionCoreCall, "CSOM runtime doesn't have Web.TitleResource and Web.DescriptionResource() methods support. Skipping validation."); assert.SkipProperty(m => m.TitleResource, "TitleResource is null or empty. Skipping."); } }
/// <summary> /// Gets the sub project items. /// </summary> /// <param name="instance">The instance.</param> /// <returns>The sub project items.</returns> public static IEnumerable <ProjectItem> GetSubProjectItems(this ProjectItem instance) { TraceService.WriteLine("ProjectItemExtensions::GetSubProjectItems file=" + instance.Name); return(instance.ProjectItems.Cast <ProjectItem>().ToList()); }
/// <summary> /// Implements the code snippet. /// </summary> /// <param name="instance">The instance.</param> /// <param name="codeSnippet">The code snippet.</param> /// <param name="formatFunctionParameters">if set to <c>true</c> [format function parameters].</param> public static void ImplementCodeSnippet( this CodeClass instance, CodeSnippet codeSnippet, bool formatFunctionParameters) { TraceService.WriteLine("CodeClassExtensions::ImplementCodeSnippet file" + instance.Name); if (codeSnippet.Variables != null) { foreach (string[] parts in codeSnippet.Variables .Select(variable => variable.Split(' '))) { //// variable could already exist! try { instance.ImplementVariable(parts[1], parts[0], false); } catch (Exception exception) { TraceService.WriteError("Error adding variable exception=" + exception.Message + " variable=" + parts[1]); //// if variable already exists get out - code snippet will already have been applied. return; } } } if (codeSnippet.MockVariables != null) { foreach (string[] parts in codeSnippet.MockVariables .Select(variable => variable.Split(' '))) { //// variable could already exist! try { instance.ImplementMockVariable(parts[1], parts[0], codeSnippet.MockingVariableDeclaration); } catch (Exception exception) { TraceService.WriteError("Error adding mock variable exception=" + exception.Message + " variable=" + parts[1]); //// if variable already exists get out - code snippet will already have been applied. return; } } } if (string.IsNullOrEmpty(codeSnippet.Code) == false) { instance.ImplementFunction(codeSnippet); } if (codeSnippet.Interfaces != null && codeSnippet.Interfaces.Count > 0) { IEnumerable <CodeFunction> constructors = instance.GetConstructors(); CodeFunction constructor = constructors.FirstOrDefault() ?? instance.AddDefaultConstructor(true); foreach (string variable in codeSnippet.Interfaces) { instance.ImplementInterface(constructor, variable); } if (formatFunctionParameters) { constructor.FormatParameters(); } } if (string.IsNullOrEmpty(codeSnippet.GetMockInitCode()) == false || string.IsNullOrEmpty(codeSnippet.GetMockConstructorCode()) == false) { instance.ImplementMockCode(codeSnippet); } }
/// <summary> /// Adds the name space. /// </summary> /// <param name="instance">The instance.</param> /// <param name="nameSpace">The name space.</param> /// <returns> /// The created name space. /// </returns> public static CodeNamespace AddNameSpace(this ProjectItem instance, string nameSpace) { TraceService.WriteLine("ProjectItemExtensions::AddNameSpace file=" + instance.Name); return(instance.ContainingProject.CodeModel.AddNamespace(nameSpace, instance.Name)); }
internal static TermStore FindTermStore(Site site, string termStoreName, Guid?termStoreId, bool?useDefaultSiteCollectionTermStore) { var clientContext = site.Context; TermStore termStore = null; lock (_storeCacheLock) { var key = string.Format("{0}-{1}-{2}", clientContext.GetHashCode(), clientContext.GetHashCode(), string.Format("{0}-{1}-{2}", termStoreName, termStoreId, useDefaultSiteCollectionTermStore)) .ToLower(); if (!_storeCache.ContainsKey(key)) { TraceService.VerboseFormat((int)LogEventId.ModelProvisionCoreCall, "First call to TermStore with cache key: [{0}]", key); var session = TaxonomySession.GetTaxonomySession(clientContext); var client = clientContext; if (useDefaultSiteCollectionTermStore == true) { TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "Resolving Term Store as useDefaultSiteCollectionTermStore"); termStore = session.GetDefaultSiteCollectionTermStore(); } else { if (termStoreId.HasValue && termStoreId != default(Guid)) { TraceService.VerboseFormat((int)LogEventId.ModelProvisionCoreCall, "Resolving Term Store by ID: [{0}]", termStoreId.Value); termStore = session.TermStores.GetById(termStoreId.Value); } else if (!string.IsNullOrEmpty(termStoreName)) { TraceService.VerboseFormat((int)LogEventId.ModelProvisionCoreCall, "Resolving Term Store by Name: [{0}]", termStoreName); termStore = session.TermStores.GetByName(termStoreName); } } if (termStore != null) { client.Load(termStore, s => s.Id); client.Load(termStore, s => s.Name); client.ExecuteQueryWithTrace(); } _storeCache.Add(key, termStore); } else { TraceService.VerboseFormat((int)LogEventId.ModelProvisionCoreCall, "Resolving term store from internal cache with cache key: [{0}]", key); } return(_storeCache[key]); } return(termStore); }
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(); } }
public override void DeployModel(object modelHost, DefinitionBase model) { var folderModelHost = modelHost.WithAssertAndCast <FolderModelHost>("modelHost", value => value.RequireNotNull()); var definition = model.WithAssertAndCast <MasterPageDefinitionBase>("model", value => value.RequireNotNull()); var folder = folderModelHost.CurrentListFolder; var list = folderModelHost.CurrentList; var context = folder.Context; var pageName = GetSafePageFileName(definition); var currentPageFile = GetCurrentPage(list, folder, pageName); InvokeOnModelEvent(this, new ModelEventArgs { CurrentModelNode = null, Model = null, EventType = ModelEventType.OnProvisioning, Object = currentPageFile, ObjectType = typeof(File), ObjectDefinition = definition, ModelHost = modelHost }); ModuleFileModelHandler.WithSafeFileOperation(list, currentPageFile, f => { var file = new FileCreationInformation(); file.Url = pageName; file.Content = definition.Content; file.Overwrite = definition.NeedOverride; return(folder.Files.Add(file)); }, newFile => { var newFileItem = newFile.ListItemAllFields; context.Load(newFileItem); context.ExecuteQueryWithTrace(); //var site = folderModelHost.HostSite; //var currentPageLayoutItem = FindPageLayoutItem(site, definition.FileName); //var currentPageLayoutItemContext = currentPageLayoutItem.Context; //var publishingFile = currentPageLayoutItem.File; //currentPageLayoutItemContext.Load(currentPageLayoutItem); //currentPageLayoutItemContext.Load(currentPageLayoutItem, i => i.DisplayName); //currentPageLayoutItemContext.Load(publishingFile); //currentPageLayoutItemContext.ExecuteQueryWithTrace(); // ** SIC.. found with Problem with url in MasterPageSettings #936 // https://github.com/SubPointSolutions/spmeta2/issues/936 // * /_catalogs/masterpage - would have 'Title' field (and correct content types) // * /my-sub-web/_catalogs/masterpage - would NOT have 'Title' fiels so that provision fails // so performing Title update only for the root web if (folderModelHost.HostSite.ServerRelativeUrl == folderModelHost.HostWeb.ServerRelativeUrl) { TraceService.VerboseFormat((int)LogEventId.ModelProvisionCoreCall, "Updating master page 'Title' on the root web.", null); newFileItem[BuiltInInternalFieldNames.Title] = definition.Title; } else { TraceService.VerboseFormat((int)LogEventId.ModelProvisionCoreCall, "Skipping master page 'Title' update. Subweb is detcted.", null); } newFileItem["MasterPageDescription"] = definition.Description; newFileItem[BuiltInInternalFieldNames.ContentTypeId] = PageContentTypeId; if (definition.UIVersion.Count > 0) { newFileItem["UIVersion"] = string.Join(";#", definition.UIVersion.ToArray()); } newFileItem["DefaultCssFile"] = definition.DefaultCSSFile; newFileItem.Update(); context.ExecuteQueryWithTrace(); }); currentPageFile = GetCurrentPage(folderModelHost.CurrentList, folder, pageName); InvokeOnModelEvent(this, new ModelEventArgs { CurrentModelNode = null, Model = null, EventType = ModelEventType.OnProvisioned, Object = currentPageFile, ObjectType = typeof(File), ObjectDefinition = definition, ModelHost = modelHost }); context.ExecuteQueryWithTrace(); }
protected void ProcessView(object modelHost, SPList targetList, ListViewDefinition listViewModel) { var currentView = FindView(targetList, listViewModel); InvokeOnModelEvent(this, new ModelEventArgs { CurrentModelNode = null, Model = null, EventType = ModelEventType.OnProvisioning, Object = currentView, ObjectType = typeof(SPView), ObjectDefinition = listViewModel, ModelHost = modelHost }); if (currentView == null) { TraceService.Information((int)LogEventId.ModelProvisionProcessingNewObject, "Processing new list view"); var viewFields = new StringCollection(); viewFields.AddRange(listViewModel.Fields.ToArray()); var isPersonalView = false; var viewType = (SPViewCollection.SPViewType)Enum.Parse(typeof(SPViewCollection.SPViewType), string.IsNullOrEmpty(listViewModel.Type) ? BuiltInViewType.Html : listViewModel.Type); // TODO, handle personal view creation currentView = targetList.Views.Add( string.IsNullOrEmpty(listViewModel.Url) ? listViewModel.Title : GetSafeViewUrl(listViewModel.Url), viewFields, listViewModel.Query, (uint)listViewModel.RowLimit, listViewModel.IsPaged, listViewModel.IsDefault, viewType, isPersonalView); currentView.Title = listViewModel.Title; } else { TraceService.Information((int)LogEventId.ModelProvisionProcessingExistingObject, "Processing existing list view"); } // viewModel.InvokeOnDeployingModelEvents<ListViewDefinition, SPView>(currentView); MapProperties(targetList, currentView, listViewModel); // viewModel.InvokeOnModelUpdatedEvents<ListViewDefinition, SPView>(currentView); ProcessLocalization(currentView, listViewModel); InvokeOnModelEvent(this, new ModelEventArgs { CurrentModelNode = null, Model = null, EventType = ModelEventType.OnProvisioned, Object = currentView, ObjectType = typeof(SPView), ObjectDefinition = listViewModel, ModelHost = modelHost }); TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "Calling currentView.Update()"); currentView.Update(); }
public override void DeployModel(object modelHost, DefinitionBase model) { this.ModelHost = modelHost; if (!(modelHost is SiteModelHost || modelHost is WebModelHost || modelHost is ListModelHost)) { throw new ArgumentException("modelHost needs to be SiteModelHost/WebModelHost/ListModelHost instance."); } CurrentHostClientContext = (modelHost as CSOMModelHostBase).HostClientContext; CurrentModelHost = modelHost.WithAssertAndCast <CSOMModelHostBase>("modelHost", value => value.RequireNotNull()); HostSite = ExtractSiteFromHost(modelHost); HostWeb = ExtractWebFromHost(modelHost); TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "Casting field model definition"); var fieldModel = model.WithAssertAndCast <FieldDefinition>("model", value => value.RequireNotNull()); Field currentField = null; ClientRuntimeContext context = null; InvokeOnModelEvent(this, new ModelEventArgs { CurrentModelNode = null, Model = null, EventType = ModelEventType.OnProvisioning, Object = null, ObjectType = GetTargetFieldType(fieldModel), ObjectDefinition = model, ModelHost = modelHost }); if (modelHost is ListModelHost) { var listHost = modelHost as ListModelHost; context = listHost.HostList.Context; currentField = DeployListField(modelHost as ListModelHost, fieldModel); } else if (modelHost is WebModelHost) { var webHost = modelHost as WebModelHost; context = webHost.HostWeb.Context; currentField = DeployWebField(webHost as WebModelHost, fieldModel); } else if (modelHost is SiteModelHost) { var siteHost = modelHost as SiteModelHost; context = siteHost.HostSite.Context; currentField = DeploySiteField(siteHost as SiteModelHost, fieldModel); } else { throw new ArgumentException("modelHost needs to be SiteModelHost/WebModelHost/ListModelHost instance."); } object typedField = null; // emulate context.CastTo<>() call for typed field type if (GetTargetFieldType(fieldModel) != currentField.GetType()) { var targetFieldType = GetTargetFieldType(fieldModel); TraceService.VerboseFormat((int)LogEventId.ModelProvisionCoreCall, "Calling context.CastTo() to field type: [{0}]", targetFieldType); var method = context.GetType().GetMethod("CastTo"); var generic = method.MakeGenericMethod(targetFieldType); typedField = generic.Invoke(context, new object[] { currentField }); } InvokeOnModelEvent(this, new ModelEventArgs { CurrentModelNode = null, Model = null, EventType = ModelEventType.OnProvisioned, Object = typedField ?? currentField, ObjectType = GetTargetFieldType(fieldModel), ObjectDefinition = model, ModelHost = modelHost }); if (fieldModel.PushChangesToLists.HasValue) { TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, string.Format("UpdateAndPushChanges({0})", fieldModel.PushChangesToLists)); currentField.UpdateAndPushChanges(fieldModel.PushChangesToLists.Value); } else { TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "UpdateAndPushChanges(true)"); // Why does SSOM handler distinguish between list and web/site fields and csom doesn't? currentField.UpdateAndPushChanges(true); } TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "ExecuteQuery()"); context.ExecuteQueryWithTrace(); CurrentHostClientContext = null; }
public override void DeployModel(object modelHost, DefinitionBase model) { var webModelHost = modelHost.WithAssertAndCast <WebModelHost>("modelHost", value => value.RequireNotNull()); var web = webModelHost.HostWeb; var listModel = model.WithAssertAndCast <ListDefinition>("model", value => value.RequireNotNull()); var context = web.Context; context.Load(web, w => w.ServerRelativeUrl); context.ExecuteQueryWithTrace(); List currentList = null; var loadedList = LoadCurrentList(web, listModel); if (loadedList != null) { currentList = loadedList; } InvokeOnModelEvent(this, new ModelEventArgs { CurrentModelNode = null, Model = null, EventType = ModelEventType.OnProvisioning, Object = null, ObjectType = typeof(List), ObjectDefinition = model, ModelHost = modelHost }); // gosh! //currentList = FindListByUrl(lists, listModel.GetListUrl()); if (currentList == null) { TraceService.Information((int)LogEventId.ModelProvisionProcessingNewObject, "Processing new list"); // no support for the TemplateName yet var listInfo = new ListCreationInformation { Title = listModel.Title, Description = listModel.Description ?? string.Empty, #pragma warning disable 618 Url = listModel.GetListUrl() #pragma warning restore 618 }; if (listModel.TemplateType > 0) { TraceService.VerboseFormat((int)LogEventId.ModelProvisionCoreCall, "Creating list by TemplateType: [{0}]", listModel.TemplateType); listInfo.TemplateType = listModel.TemplateType; } else if (!string.IsNullOrEmpty(listModel.TemplateName)) { TraceService.VerboseFormat((int)LogEventId.ModelProvisionCoreCall, "Creating list by TemplateName: [{0}]", listModel.TemplateName); var listTemplate = ResolveListTemplate(webModelHost, listModel); listInfo.TemplateFeatureId = listTemplate.FeatureId; listInfo.TemplateType = listTemplate.ListTemplateTypeKind; } else { TraceService.Error((int)LogEventId.ModelProvisionCoreCall, "Either TemplateType or TemplateName has to be specified. Throwing SPMeta2Exception"); throw new SPMeta2Exception("Either TemplateType or TemplateName has to be specified."); } var newList = web.Lists.Add(listInfo); currentList = newList; currentList.Update(); context.ExecuteQueryWithTrace(); currentList = LoadCurrentList(web, listModel); } else { TraceService.Information((int)LogEventId.ModelProvisionProcessingExistingObject, "Processing existing list"); } MapListProperties(currentList, listModel); InvokeOnModelEvent(this, new ModelEventArgs { CurrentModelNode = null, Model = null, EventType = ModelEventType.OnProvisioned, Object = currentList, ObjectType = typeof(List), ObjectDefinition = model, ModelHost = modelHost }); TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "Calling currentList.Update()"); currentList.Update(); context.ExecuteQueryWithTrace(); }
private SPField DeployListField(SPList list, FieldDefinition fieldModel) { TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "Deploying list field"); return(EnsureFieldInFieldsCollection(list, list.Fields, fieldModel)); }
/// <summary> /// Gets the solution. /// </summary> /// <param name="instance">The instance.</param> /// <returns>The solution.</returns> public static Solution GetSolution(this DTE2 instance) { TraceService.WriteLine("DTEExtensions::GetSolution"); return(instance.Solution); }