public override void Execute() { DTE dte = (DTE)this.GetService(typeof(DTE)); Project project = this.GetTargetProject(dte); //1. get correct parameters ("$(FeatureName)" as "FeatureX") string evaluatedParentFeatureName = EvaluateParameterAsString(dte, ParentFeatureName); string evaluatedSPDataTemplate = EvaluateParameterAsString(dte, SPDataTemplate); string evaluatedElementsTemplate = EvaluateParameterAsString(dte, TemplateFileName); string evaluatedElementsCategory = EvaluateParameterAsString(dte, ElementsCategory); string evaluatedElementsName = EvaluateParameterAsString(dte, ElementsName); string evaluatedTargetFileName = EvaluateParameterAsString(dte, TargetFileName); string evaluatedDeploymentPath = EvaluateParameterAsString(dte, DeploymentPath); if (string.IsNullOrEmpty(evaluatedTargetFileName)) { evaluatedTargetFileName = "Elements.xml"; } //2. create the Element if (Helpers2.IsSharePointVSTemplate(dte, project)) { AddElementsDefinitionToVSTemplate(dte, project, evaluatedParentFeatureName, evaluatedSPDataTemplate, evaluatedElementsTemplate, evaluatedElementsCategory, evaluatedElementsName, evaluatedTargetFileName); } }
private void AddApplicationResources(Project _CurrentProject, string resourcefilename, string content) { if (Helpers2.IsSharePointVSTemplate(_CurrentProject.DTE, _CurrentProject)) { AddResources(_CurrentProject, "Resources\\AppGlobalResources", resourcefilename, content, SPFileType.AppGlobalResource, ""); } else { //deploy resx file to 14\Config\Resources ProjectItems whereToAdd = Helpers2.GetDeploymentPath(_CurrentProject.DTE, _CurrentProject, SPFileType.RootFile, "CONFIG\\Resources"); AddResourcesToFolder(whereToAdd.Parent as ProjectItem, resourcefilename, content); } }
private void AddAdminResources(Project _CurrentProject, string resourcefilename, string content) { //files for central administration if (Helpers2.IsSharePointVSTemplate(_CurrentProject.DTE, _CurrentProject)) { AddResources(_CurrentProject, "Resources\\AppGlobalResources", resourcefilename, content, SPFileType.AppGlobalResource, ""); } else { ProjectItems whereToAdd = Helpers2.GetDeploymentPath(_CurrentProject.DTE, _CurrentProject, SPFileType.RootFile, "CONFIG\\AdminResources"); AddResourcesToFolder(whereToAdd.Parent as ProjectItem, resourcefilename, content); } }
private void AddGlobalResources(Project _CurrentProject, string resourcefilename, string content) { if (Helpers2.IsSharePointVSTemplate(_CurrentProject.DTE, _CurrentProject)) { AddResources(_CurrentProject, "Resources\\Resources", resourcefilename, content, SPFileType.RootFile, "Resources"); } else { //get the folder where to place the resx file ProjectItems whereToAdd = Helpers2.GetDeploymentPath(_CurrentProject.DTE, _CurrentProject, SPFileType.RootFile, "Resources"); AddResourcesToFolder(whereToAdd.Parent as ProjectItem, resourcefilename, content); } }
public override void Execute() { DTE dte = (DTE)this.GetService(typeof(DTE)); Project project = this.GetTargetProject(dte); //Microsoft.Practices.RecipeFramework.GuidancePackage p = (Microsoft.Practices.RecipeFramework.GuidancePackage)GetService(typeof(Microsoft.Practices.RecipeFramework.Services.IExecutionService)); //ISite x = p.Site; //1. get correct parameters ("$(FeatureName)" as "FeatureX") string evaluatedFeatureName = EvaluateParameterAsString(dte, featureName); //2. create the Feature if (Helpers2.IsSharePointVSTemplate(dte, project)) { AddFeatureToVSTemplate(dte, project, evaluatedFeatureName); } }
public override void Execute() { DTE dte = GetService <DTE>(true); Project project = TargetProject; if (project == null) { project = Helpers.GetSelectedProject(dte); } if (Helpers2.IsSharePointVSTemplate(dte, project)) { Helpers2.GetOrCreateMappedFolder(project, "RootFile", "SharePointRoot"); } Helpers.ExtractWSPToProject(dte, _WSPFilename, _TargetProject, GetBasePath()); }
//[Output] //public ProjectItem CreatedProjectFolder { get; set; } //[Output] //public ProjectItem CreatedProjectItem { get; set; } public override void Execute() { DTE dte = (DTE)this.GetService(typeof(DTE)); Project project = this.GetTargetProject(dte); string evaluatedSPDataTemplate = EvaluateParameterAsString(dte, SPDataTemplate); string evaluatedTemplate = EvaluateParameterAsString(dte, TemplateFileName); string evaluatedSPDataCategory = EvaluateParameterAsString(dte, SPDataCategory); string evaluatedSPDataName = EvaluateParameterAsString(dte, SPDataName); string evaluatedTargetFileName = EvaluateParameterAsString(dte, TargetFileName); string evaluatedDeploymentPath = EvaluateParameterAsString(dte, DeploymentPath); //2. create the Element if (Helpers2.IsSharePointVSTemplate(dte, project)) { AddSPDataDefinitionToVSTemplate(dte, project, evaluatedSPDataTemplate, evaluatedTemplate, evaluatedSPDataCategory, evaluatedSPDataName, evaluatedTargetFileName, evaluatedDeploymentPath); } else { base.Execute(); } }
private void AddFileInternal(DTE dte, Project project, string evaluatedSourceFileName, string evaluatedTargetFileName, string evaluatedDeploymentPath) { if (!Path.IsPathRooted(evaluatedSourceFileName)) { evaluatedSourceFileName = Path.Combine(GetTemplateBasePath(), evaluatedSourceFileName); } //ok, check the parameters if (!File.Exists(evaluatedSourceFileName)) { //ignore this action if no source file is found, used e.g. in contenttype when no file is given return; } if (string.IsNullOrEmpty(evaluatedTargetFileName)) { evaluatedTargetFileName = Path.GetFileName(evaluatedSourceFileName); } //targetfolder specified, find the project item if (!string.IsNullOrEmpty(TargetFolder) && (ParentProjectFolder == null)) { //overwrite target folder ParentProjectFolder = Helpers.GetFolder(project, TargetFolder, true); CreatedProjectFolder = this.ParentProjectFolder; } if (Helpers2.IsSharePointVSTemplate(dte, project)) { if (this.ParentProjectItem != null) { //used to add code files to a parent file CreatedProjectItem = Helpers.AddFromTemplate(ParentProjectItem.ProjectItems, evaluatedSourceFileName, evaluatedTargetFileName, Overwrite); if (DeploymentTypeIsSet) { SetDeploymentPath(dte, project, CreatedProjectItem, this.DeploymentType, evaluatedDeploymentPath); } } else if (this.ParentProjectFolder != null) { //we place the file directly in the given folder //and mapped the item to the deployment location CreatedProjectItem = Helpers.AddFromTemplate(this.ParentProjectFolder.ProjectItems, evaluatedSourceFileName, evaluatedTargetFileName, Overwrite); if (DeploymentTypeIsSet) { SetDeploymentPath(dte, project, CreatedProjectItem, this.DeploymentType, evaluatedDeploymentPath); } } else if (DeploymentTypeIsSet) { //place the file in a mapped folder ProjectItems whereToAdd = Helpers2.GetDeploymentPath(dte, project, this.DeploymentType, evaluatedDeploymentPath); CreatedProjectItem = Helpers.AddFromTemplate(whereToAdd, evaluatedSourceFileName, evaluatedTargetFileName, Overwrite); //do not set the deploymentpath as we already placed the file in the mapped folder location } else if (project != null) { CreatedProjectItem = Helpers.AddFromTemplate(project.ProjectItems, evaluatedSourceFileName, evaluatedTargetFileName, Overwrite); } else { throw new Exception("Don't know where to place the file"); } } if (CreatedProjectItem != null) { //set the build action if (CreatedProjectItem.Name.EndsWith(".resx", StringComparison.InvariantCultureIgnoreCase)) { CreatedProjectItem.Properties.Item("BuildAction").Value = 2; } } if (this.Open) { if (this.CreatedProjectItem != null) { Window window = this.CreatedProjectItem.Open("{00000000-0000-0000-0000-000000000000}"); window.Visible = true; window.Activate(); } } }
public override void Execute() { DTE service = (DTE)this.GetService(typeof(DTE)); Helpers.ShowProgress(service, "Generating WSDL...", 10); string defaultIISAPP = Helpers.GetDefaultIISWebApp(); string workingDirectory = Path.Combine(Path.GetTempPath(), "SPALMWSDL" + Guid.NewGuid().ToString()); Directory.CreateDirectory(workingDirectory); ProjectItem asmxfileParentFolder = (ProjectItem)WebServiceFile.ProjectItems.Parent; //build if necessary Helpers.WriteToOutputWindow(service, "Compile to get actual version of dll"); Project project = WebServiceFile.ContainingProject; service.Solution.SolutionBuild.BuildProject(service.Solution.SolutionBuild.ActiveConfiguration.Name, project.UniqueName, true); //get the asmx file and copy to /_layouts string projectpath = Helpers.GetFullPathOfProjectItem(project); string projectfolder = Path.GetDirectoryName(projectpath); bool ASMXFileExisted = false; string fullasmxtarget = ""; string asmxfilename = WebServiceFile.Name; string asmxfilenamewithoutext = asmxfilename.Substring(0, asmxfilename.LastIndexOf(".")); string asmxfullPath = Helpers.GetFullPathOfProjectItem(WebServiceFile); if (File.Exists(asmxfullPath)) { string targetfolder = Helpers.GetSharePointHive() + @"\TEMPLATE\LAYOUTS"; Helpers.WriteToOutputWindow(service, "Copying asmx file to _layouts folder"); fullasmxtarget = Path.Combine(targetfolder, asmxfilename); if (File.Exists(fullasmxtarget)) { ASMXFileExisted = true; } File.Copy(asmxfullPath, fullasmxtarget, true); } //add the assembly to the gac string OutputFileName = project.Properties.Item("OutputFileName").Value.ToString(); string OutputPath = project.ConfigurationManager.ActiveConfiguration.Properties.Item("OutputPath").Value.ToString(); string assemblypath = Path.Combine(Path.Combine(projectfolder, OutputPath), OutputFileName); if (!File.Exists(assemblypath)) { //check GAC folder of project assemblypath = Path.Combine(projectfolder, "GAC"); if (Directory.Exists(assemblypath)) { assemblypath = Path.Combine(assemblypath, OutputFileName); } } if (!File.Exists(assemblypath)) { string message = "Warning: No assembly in project found"; Helpers.LogMessage(service, this, message); MessageBox.Show(message); } if (File.Exists(assemblypath)) { string gacutilpath = Helpers.GetGACUtil(service); //sear if (File.Exists(gacutilpath)) { Helpers.ShowProgress(service, "Generating WSDL...", 30); Helpers.WriteToOutputWindow(service, "Install dll in GAC", false); Helpers.RunProcess(service, gacutilpath, "/if " + assemblypath, true, workingDirectory, false); Helpers.WriteToOutputWindow(service, "IISReset to force reload of dll", false); Helpers.ShowProgress(service, "Generating WSDL...", 60); Helpers.LogMessage(service, this, "IISRESET..."); Helpers.RunProcess(service, "iisreset", "", true, workingDirectory, false); } else { string message = "GACUTIL.exe not found on your system.\nPlease install .net or Windows SDK.\ni.e. Windows SDK 7.1 http://www.microsoft.com/download/en/details.aspx?id=8442"; Helpers.LogMessage(service, this, message); MessageBox.Show(message); } } //call disco.exe Helpers.LogMessage(service, this, "Getting path to disco.exe..."); string discopath = Helpers.GetDiscoPath(); if (discopath != "") { if (!defaultIISAPP.StartsWith("http:")) { defaultIISAPP = "http://" + defaultIISAPP; } Helpers.ShowProgress(service, "Generating WSDL...", 80); string discoargument = " " + defaultIISAPP + "/_layouts" + Helpers.GetVersionedFolder(service) + "/" + asmxfilename; Helpers.LogMessage(service, this, "Ping server..."); DeploymentHelpers.PingServer(service, discoargument, 20000); Helpers.LogMessage(service, this, "Running disco.exe..."); Helpers.RunProcess(service, discopath, discoargument, true, workingDirectory, false); } else { string message = "Disco.exe not found on your system.\nPlease install .net or Windows SDK.\ni.e. Windows SDK 7.1 http://www.microsoft.com/download/en/details.aspx?id=8442"; Helpers.LogMessage(service, this, message); MessageBox.Show(message); } //adding results to the project //WebService1.disco string finalwsdlpath = ""; string finaldiscopath = ""; string[] wsdls = Directory.GetFiles(workingDirectory, "*.wsdl"); if (wsdls.Length > 0) { finalwsdlpath = wsdls[0]; } string[] discos = Directory.GetFiles(workingDirectory, "*.disco"); if (discos.Length > 0) { finaldiscopath = discos[0]; } if (File.Exists(finalwsdlpath) && File.Exists(finaldiscopath)) { string SharePointVersion = Helpers.GetInstalledSharePointVersion(); //replace text in the files /*To register namespaces of the Windows SharePoint Services object model, open both the .disco and .wsdl files and replace the opening XML processing instruction -- <?xml version="1.0" encoding="utf-8"?> -- with instructions such as the following: * <%@ Page Language="C#" Inherits="System.Web.UI.Page" %> * <%@ Assembly Name="Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %> * <%@ Import Namespace="Microsoft.SharePoint.Utilities" %> * <%@ Import Namespace="Microsoft.SharePoint" %> * <% Response.ContentType = "text/xml"; %> */ Helpers.ShowProgress(service, "Generating WSDL...", 90); StringBuilder wsdlreplaced = new StringBuilder(); TextReader wsdlreader = new StreamReader(finalwsdlpath); string input = null; while ((input = wsdlreader.ReadLine()) != null) { if (input.TrimStart(null).StartsWith("<?xml version=")) { wsdlreplaced.AppendLine("<%@ Page Language=\"C#\" Inherits=\"System.Web.UI.Page\" %>"); wsdlreplaced.AppendLine("<%@ Assembly Name=\"Microsoft.SharePoint, Version=" + SharePointVersion + ".0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c\" %>"); wsdlreplaced.AppendLine("<%@ Import Namespace=\"Microsoft.SharePoint.Utilities\" %> "); wsdlreplaced.AppendLine("<%@ Import Namespace=\"Microsoft.SharePoint\" %>"); wsdlreplaced.AppendLine("<% Response.ContentType = \"text/xml\"; %>"); } else if (input.TrimStart(null).StartsWith("<soap:address")) { wsdlreplaced.AppendLine("<soap:address location=<% SPHttpUtility.AddQuote(SPHttpUtility.HtmlEncode(SPWeb.OriginalBaseUrl(Request)),Response.Output); %> />"); } else if (input.TrimStart(null).StartsWith("<soap12:address")) { wsdlreplaced.AppendLine("<soap12:address location=<% SPHttpUtility.AddQuote(SPHttpUtility.HtmlEncode(SPWeb.OriginalBaseUrl(Request)),Response.Output); %> />"); } else { wsdlreplaced.AppendLine(input); } } wsdlreader.Close(); TextWriter wsdlwriter = new StreamWriter(finalwsdlpath); wsdlwriter.Write(wsdlreplaced.ToString()); wsdlwriter.Close(); StringBuilder discoreplaced = new StringBuilder(); TextReader discoreader = new StreamReader(finaldiscopath); string discoinput = null; while ((discoinput = discoreader.ReadLine()) != null) { if (discoinput.TrimStart(null).StartsWith("<?xml version=")) { discoreplaced.AppendLine("<%@ Page Language=\"C#\" Inherits=\"System.Web.UI.Page\" %>"); discoreplaced.AppendLine("<%@ Assembly Name=\"Microsoft.SharePoint, Version=" + SharePointVersion + ".0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c\" %>"); discoreplaced.AppendLine("<%@ Import Namespace=\"Microsoft.SharePoint.Utilities\" %> "); discoreplaced.AppendLine("<%@ Import Namespace=\"Microsoft.SharePoint\" %>"); discoreplaced.AppendLine("<% Response.ContentType = \"text/xml\"; %>"); } else if (discoinput.TrimStart(null).StartsWith("<contractRef")) { discoreplaced.AppendLine("<contractRef ref=<% SPHttpUtility.AddQuote(SPHttpUtility.HtmlEncode(SPWeb.OriginalBaseUrl(Request) + \"?wsdl\"),Response.Output); %> docRef=<% SPHttpUtility.AddQuote(SPHttpUtility.HtmlEncode(SPWeb.OriginalBaseUrl(Request)),Response.Output); %> xmlns=\"http://schemas.xmlsoap.org/disco/scl/\" />"); } else if (discoinput.TrimStart(null).StartsWith("<soap address=")) { //before //<soap address="http://tfsrtm08/_layouts/WebService1.asmx" xmlns:q1="http://SMC.Supernet.Web.WebServices/" binding="q1:WebService1Soap" xmlns="http://schemas.xmlsoap.org/disco/soap/" /> //replaced //<soap address=<% SPHttpUtility.AddQuote(SPHttpUtility.HtmlEncode(SPWeb.OriginalBaseUrl(Request)),Response.Output); %> xmlns:q1="http://tempuri.org/" binding="q1:HelloWorld" xmlns="http://schemas.xmlsoap.org/disco/soap/" /> //we replace the field adress string originalstring = discoinput; string beforeaddress = originalstring.Substring(0, originalstring.IndexOf(" address=") + 9); string afteraddress = originalstring.Substring(originalstring.IndexOf("\"", originalstring.IndexOf(" address=") + 11)); //skip the quot afteraddress = afteraddress.Substring(1); discoreplaced.AppendLine(beforeaddress + "<% SPHttpUtility.AddQuote(SPHttpUtility.HtmlEncode(SPWeb.OriginalBaseUrl(Request)),Response.Output); %>" + afteraddress); } else { discoreplaced.AppendLine(discoinput); } } discoreader.Close(); TextWriter discowriter = new StreamWriter(finaldiscopath); discowriter.Write(discoreplaced.ToString()); discowriter.Close(); //files renaming needed //WebService.wsdl -> WebServiceWSDL.aspx //WebService.disco -> WebServiceDisco.aspx string renamedwsdlpath = Path.Combine(workingDirectory, asmxfilenamewithoutext + "WSDL.aspx"); string renameddiscopath = Path.Combine(workingDirectory, asmxfilenamewithoutext + "Disco.aspx"); File.Copy(finalwsdlpath, renamedwsdlpath); File.Copy(finaldiscopath, renameddiscopath); //add the files to the project ProjectItem wsdlItem = Helpers.AddFile(asmxfileParentFolder, renamedwsdlpath); ProjectItem discoItem = Helpers.AddFile(asmxfileParentFolder, renameddiscopath); //set the deployment target of the files to the same as the parent if (Helpers2.IsSharePointVSTemplate(service, project)) { Helpers2.CopyDeploymentPath(WebServiceFile, wsdlItem); Helpers2.CopyDeploymentPath(WebServiceFile, discoItem); } } else { string message = "Created WSDL and DISCO files not found. Creation failed."; Helpers.LogMessage(service, this, message); MessageBox.Show(message); } try { //delete temp folder Directory.Delete(workingDirectory, true); //clean up everything what we have copied to the layouts folder if (ASMXFileExisted) { File.Delete(fullasmxtarget); } } catch (Exception) { } Helpers.HideProgress(service); }
public override void Execute() { if (ExcludeCondition) { return; } if (!AdditionalCondition) { return; } DTE dte = (DTE)this.GetService(typeof(DTE)); Project project = this.GetTargetProject(dte); string evaluatedTemplateFileName = EvaluateParameterAsString(dte, TemplateFileName); string templateContent = GenerateContent(evaluatedTemplateFileName, "Resources.resx"); if (Helpers2.TemplateContentIsEmpty(templateContent)) { //do nothing if no content has been generated return; } //get the project where we pla Project globalresproject = Helpers.GetResourcesProject(dte); Project selectedproject = Helpers.GetSelectedProject(dte); string resourcesFilename = ""; if (FeatureResources) { //for feature resources name is "Resources.resx" resourcesFilename = "Resources.resx"; } else if (ApplicationResources) { resourcesFilename = Helpers.GetOutputNameWithoutExtensions(selectedproject) + ".AppResources.resx"; } else { //global resources get the name of the current project project resourcesFilename = Helpers.GetOutputNameWithoutExtensions(selectedproject) + ".resx"; } //1. find a resourcefile if (ApplicationResources) { if (globalresproject != null) { //global resources project -> use the file 12/resources AddApplicationResources(globalresproject, resourcesFilename, templateContent); } else { AddApplicationResources(selectedproject, resourcesFilename, templateContent); } } else if (FeatureResources) { string evaluatedFeatureName = EvaluateParameterAsString(dte, FeatureName); //Find the feature folder ProjectItem folderOfFeature = Helpers2.GetFolderOfFeature(project, evaluatedFeatureName); if (folderOfFeature != null) { if (Helpers2.IsSharePointVSTemplate(dte, project)) { //put resources.resx directly into under the feature AddResourcesToFolder(folderOfFeature, resourcesFilename, templateContent); } else { //now add a folder "Resources" in the feature and put the "Resource.<culture>.resx" there ProjectItems whereToAdd = Helpers.GetProjectItemsByPath(folderOfFeature.ProjectItems, "Resources"); AddResourcesToFolder(whereToAdd.Parent as ProjectItem, resourcesFilename, templateContent); } } } else if (AdminResources) { //put the content into if (globalresproject != null) { //global resources project -> use the file 12/resources AddAdminResources(globalresproject, resourcesFilename, templateContent); } else { AddAdminResources(selectedproject, resourcesFilename, templateContent); } } else { //put the content into if (globalresproject != null) { //global resources project -> use the file 12/resources AddGlobalResources(globalresproject, resourcesFilename, templateContent); } else { AddGlobalResources(selectedproject, resourcesFilename, templateContent); } } }
public override void Execute() { if (ExcludeCondition) { return; } if (!AdditionalCondition) { return; } DTE dte = (DTE)this.GetService(typeof(DTE)); Project project = this.GetTargetProject(dte); string evaluatedTemplateFileName = EvaluateParameterAsString(dte, TemplateFileName); string templateContent = GenerateContent(evaluatedTemplateFileName, "CASPolicy.txt"); if (Helpers2.TemplateContentIsEmpty(templateContent)) { //do nothing if no content has been generated return; } if (Helpers2.IsSharePointVSTemplate(dte, project)) { Helpers.LogMessage(dte, this, "Adding CAS Policy to file 'Package/Package.Template.xml"); //merge the contents with the cas policy in the package //find the package/package.Template.xml try { ProjectItem packageItem = Helpers.GetProjectItemByName(Helpers.GetProjectItemByName(project.ProjectItems, "Package").ProjectItems, "Package.Template.xml"); if (packageItem == null) { packageItem = Helpers.GetProjectItemByName(Helpers.GetProjectItemByName(Helpers.GetProjectItemByName(project.ProjectItems, "Package").ProjectItems, "Package.package").ProjectItems, "Package.Template.xml"); } if (packageItem != null) { Helpers.EnsureCheckout(dte, packageItem); string packageFilepath = Helpers.GetFullPathOfProjectItem(packageItem); XmlDocument packageXml = new XmlDocument(); packageXml.Load(packageFilepath); XmlNodeList permissionSetNodes = null; //1. if there is no node Solution/CodeAccessSecurity then we add a new one automatically XmlNamespaceManager featurensmgr = new XmlNamespaceManager(packageXml.NameTable); featurensmgr.AddNamespace("ns", "http://schemas.microsoft.com/sharepoint/"); XmlNodeList allCodeAccessSecurityNodes = packageXml.SelectNodes("ns:Solution/ns:CodeAccessSecurity", featurensmgr); if (allCodeAccessSecurityNodes.Count == 0) { //add default cas policy element string templateFilepath = Path.Combine(GetTemplateBasePath(), "Text\\CodeAccessSecurity.xml"); XmlDocument resdoc = new XmlDocument(); resdoc.Load(templateFilepath); //select the solution node XmlNode solutionNode = packageXml.SelectSingleNode("ns:Solution", featurensmgr); XmlDocumentFragment docFrag = packageXml.CreateDocumentFragment(); docFrag.InnerXml = "<dummy xmlns='http://schemas.microsoft.com/sharepoint/'>" + resdoc.OuterXml + "</dummy>"; solutionNode.AppendChild(docFrag.FirstChild.FirstChild); //CleanNamespace(solutionNode); //select the nodes again allCodeAccessSecurityNodes = packageXml.SelectNodes("ns:Solution/ns:CodeAccessSecurity", featurensmgr); } permissionSetNodes = packageXml.SelectNodes("ns:Solution/ns:CodeAccessSecurity/ns:PolicyItem/ns:PermissionSet", featurensmgr); //now append the IPolicies to all existing PermissionSets XmlDocument generatedCASPolicy = new XmlDocument(); generatedCASPolicy.LoadXml(templateContent); XmlNodeList generatedIPermissions = generatedCASPolicy.SelectNodes("PermissionSet/IPermission"); //remove duplicate class foreach (XmlNode permissionSetNode in permissionSetNodes) { foreach (XmlNode generatedIPermission in generatedIPermissions) { //compare new IPermission with existing permission RemoveDuplicateClass(permissionSetNode, generatedIPermission); } //CleanNamespace(permissionSetNode); } foreach (XmlNode permissionSetNode in permissionSetNodes) { foreach (XmlNode generatedIPermission in generatedIPermissions) { XmlDocumentFragment docFrag = packageXml.CreateDocumentFragment(); docFrag.InnerXml = "<dummy xmlns='http://schemas.microsoft.com/sharepoint/'>" + generatedIPermission.OuterXml + "</dummy>"; permissionSetNode.AppendChild(docFrag.FirstChild.FirstChild); } } XmlWriter xw2 = XmlWriter.Create(packageFilepath, Helpers.GetXmlWriterSettingsAttributesInOneLine()); packageXml.Save(xw2); xw2.Flush(); xw2.Close(); Window window = packageItem.Open("{00000000-0000-0000-0000-000000000000}"); window.Visible = true; window.Activate(); } } catch { Helpers.LogMessage(dte, this, "Could not add CAS policy to package"); } } else { //add the file directly into the root this.TargetFileName = "CASPolicy.txt"; base.Execute(); } }
public override void Execute() { DTE dte = (DTE)this.GetService(typeof(DTE)); Project Project = this.GetTargetProject(dte); string evaluatedTemplateFileName = EvaluateParameterAsString(dte, TemplateFileName); string evaluatedParentFeatureName = EvaluateParameterAsString(dte, ParentFeatureName); string evaluatedAssemblyName = EvaluateParameterAsString(dte, AssemblyName); string evaluatedNamespace = EvaluateParameterAsString(dte, Namespace); string xmlContent = GenerateContent(evaluatedTemplateFileName, "ReceiverCode.xml"); try { //feature name consists of application name + SPSFConstants.NameSeparator + featurename, but we need to strip off the feature name from that string appName = Helpers.GetSaveApplicationName(dte); string featureName = evaluatedParentFeatureName; if (featureName.StartsWith(appName, StringComparison.InvariantCultureIgnoreCase)) { featureName = featureName.Substring(appName.Length + 1); } string FeatureReceiverClass = featureName + "EventReceiver"; if (Helpers2.IsSharePointVSTemplate(dte, Project)) { //can we cast the project to ISharePointSolution ISharePointProjectService projectService = Helpers2.GetSharePointProjectService(Project.DTE); ISharePointProject sharePointProject = projectService.Convert <EnvDTE.Project, ISharePointProject>(Project); sharePointProject.Synchronize(); ISharePointProjectFeature parentfeature = null; foreach (ISharePointProjectFeature feature in sharePointProject.Features) { if (feature.Name == evaluatedParentFeatureName) { parentfeature = feature; } } if (parentfeature != null) { if (string.IsNullOrEmpty(parentfeature.Model.ReceiverClass)) { if (dte.SuppressUI || (MessageBox.Show("Feature '" + evaluatedParentFeatureName + "' contains no feature receiver. Add feature receiver?", "Add Feature Receiver?", MessageBoxButtons.YesNo) == DialogResult.Yes)) { ProjectItem projectItem = projectService.Convert <ISharePointProjectFeature, EnvDTE.ProjectItem>(parentfeature); ProjectItem featureXmlFile = projectService.Convert <ISharePointProjectMember, EnvDTE.ProjectItem>(parentfeature.FeatureFile); //no feature receiver there, we create one ProjectItem createdFeatureReceiverItem = CreateNewFeatureReceiver(featureName, projectItem, featureXmlFile); parentfeature.Model.ReceiverAssembly = evaluatedAssemblyName; parentfeature.Model.ReceiverClass = evaluatedNamespace + "." + FeatureReceiverClass; this.MergeNewCodeWithClass(createdFeatureReceiverItem, FeatureReceiverClass, xmlContent); sharePointProject.Synchronize(); //is test run save file if (dte.SuppressUI) { featureXmlFile.Save(); //createdFeatureReceiverItem.Save(); } } else { return; } } else { //1. we check if there is a filename with .generated in it //we need the class name of the featurereceiver, but in VS-Feature the name contains a ID string className = parentfeature.Model.ReceiverClass; if (className.StartsWith("$SharePoint.Type")) { //not supported??? if (parentfeature.EventReceiverFile != null) { ProjectItem existingCode = projectService.Convert <ISharePointProjectMember, EnvDTE.ProjectItem>(parentfeature.EventReceiverFile); this.MergeNewCodeWithClass(existingCode, "", xmlContent); } } else { string foundReceiverClassName = parentfeature.Model.ReceiverClass; string receiverNamespace = foundReceiverClassName.Substring(0, foundReceiverClassName.LastIndexOf(".") - 1); string receiverClassName = foundReceiverClassName.Substring(foundReceiverClassName.LastIndexOf(".") + 1); //ok, class name found //yes, there is a feature receiver, but we need to find the class in the project //find any .cs item which contains the name of the featureclass and namespace List <string> patterns = new List <string>(); patterns.Add(receiverNamespace); patterns.Add(receiverClassName); patterns.Add(" FeatureActivated("); //to ensure that we get the correct partial class ProjectItem existingCode = Helpers.FindItem(Project, ".cs", patterns); if (existingCode != null) { this.MergeNewCodeWithClass(existingCode, receiverClassName, xmlContent); } } } } } else { //find the feature receiver code ProjectItem featureXMLFile = Helpers.GetFeatureXML(Project, evaluatedParentFeatureName); ProjectItem featureFolder = Helpers2.GetFeature(Project.DTE, Project, evaluatedParentFeatureName); //check if feature already contains feature receiver if (featureXMLFile != null) { string receiverClassName = Helpers.GetFeatureReceiverClass(featureXMLFile); string receiverNamespace = Helpers.GetFeatureReceiverNamespace(featureXMLFile); if (receiverClassName == "") { if (dte.SuppressUI || (MessageBox.Show("Feature '" + evaluatedParentFeatureName + "' contains no feature receiver. Add feature receiver?", "Add Feature Receiver?", MessageBoxButtons.YesNo) == DialogResult.Yes)) { //there is no feature receiver, we need to create one :-( string path = Helpers.GetFullPathOfProjectItem(featureXMLFile); XmlDocument doc = new XmlDocument(); doc.Load(path); XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable); nsmgr.AddNamespace("ns", "http://schemas.microsoft.com/sharepoint/"); XmlNode node = doc.SelectSingleNode("/ns:Feature", nsmgr); if (node != null) { ProjectItem createdFeatureReceiverItem = CreateNewFeatureReceiver(featureName, featureFolder, featureXMLFile); XmlAttribute receiverAssemblyAttrib = doc.CreateAttribute("ReceiverAssembly"); receiverAssemblyAttrib.Value = evaluatedAssemblyName; node.Attributes.Append(receiverAssemblyAttrib); XmlAttribute receiverClassAttrib = doc.CreateAttribute("ReceiverClass"); receiverClassAttrib.Value = evaluatedNamespace + "." + FeatureReceiverClass; node.Attributes.Append(receiverClassAttrib); Helpers.EnsureCheckout(dte, path); XmlWriter xw = XmlWriter.Create(path, Helpers.GetXmlWriterSettings(path)); doc.Save(xw); xw.Flush(); xw.Close(); this.MergeNewCodeWithClass(createdFeatureReceiverItem, FeatureReceiverClass, xmlContent); } } else { return; } } else { //yes, there is a feature receiver, but we need to find the class in the project //find any .cs item which contains the name of the featureclass and namespace List <string> patterns = new List <string>(); patterns.Add(receiverClassName); patterns.Add(receiverNamespace); patterns.Add(" FeatureActivated("); //to ensure that we get the correct partial class ProjectItem existingCode = Helpers.FindItem(Project, ".cs", patterns); if (existingCode != null) { //find the activated Function string featureFilename = Helpers.GetFullPathOfProjectItem(existingCode); this.MergeNewCodeWithClass(existingCode, receiverClassName, xmlContent); } } } if (featureXMLFile != null) { CreatedProjectItem = featureXMLFile; } else { CreatedProjectItem = Helpers.GetFeatureXML(Project, evaluatedParentFeatureName); } if (featureFolder != null) { CreatedProjectFolder = featureFolder; } else { CreatedProjectFolder = Helpers2.GetFeature(Project.DTE, Project, evaluatedParentFeatureName); } } } catch (Exception ex) { if (dte.SuppressUI) { throw new Exception(ex.ToString()); } else { MessageBox.Show(ex.ToString()); } } }
private void MigrateCustomizationProject(DTE service, Project project) { Helpers.EnsureCheckout(service, project); Helpers.LogMessage(service, this, "*** Migrating project '" + project.Name + "' ****"); if (Helpers2.IsSharePointVSTemplate(service, project)) { try { ProjectItem packageGeneratorTT = Helpers.GetProjectItemByName(Helpers.GetProjectItemByName(project.ProjectItems, "Package").ProjectItems, "Package.Generator.tt"); if (packageGeneratorTT != null) { Helpers.LogMessage(service, this, "Deleting Package/Package.Generator.tt"); Helpers.EnsureCheckout(service, packageGeneratorTT); packageGeneratorTT.Delete(); } } catch { Helpers.LogMessage(service, this, "Warning: Could not delete Package/Package.Generator.tt"); } try { ProjectItem packageGeneratorTMP = Helpers.GetProjectItemByName(Helpers.GetProjectItemByName(project.ProjectItems, "Package").ProjectItems, "Package.Generator.tmp"); if (packageGeneratorTMP != null) { Helpers.LogMessage(service, this, "Deleting Package/Package.Generator.tmp"); Helpers.EnsureCheckout(service, packageGeneratorTMP); packageGeneratorTMP.Delete(); } } catch { Helpers.LogMessage(service, this, "Warning: Could not delete Package/Package.Generator.tmp"); } Helpers.LogMessage(service, this, "Settings IncludeAssemblyInPackge to True"); try { Helpers.SetProjectPropertyGroupValue(project, "IncludeAssemblyInPackage", "True"); } catch { } } //4. add property Sandboxedsolution if property is not available try { string testvalue = Helpers.GetProjectPropertyGroupValue(project, "Sandboxedsolution", "NOTFOUND").ToString(); if (testvalue == "NOTFOUND") { Helpers.LogMessage(service, this, "Updated project property 'Sandboxedsolution'"); Helpers.SetProjectPropertyGroupValue(project, "Sandboxedsolution", "False"); } } catch { } try { string nameOfProject = project.Name; //Helpers2.MoveProjectToSolutionFolder(service, project.Name, "Solutions"); //after moving we need to get the moved project again from the name project = Helpers.GetProjectByName(service, nameOfProject); } catch { } //5. Add import to SharePoint.targets (e.g. for WSP projects) string fileName = project.FullName; Helpers.SelectProject(project); if (service.SuppressUI || MessageBox.Show("The project file of project " + project.Name + " must be updated. Can SPSF save and unload the project?", "Unloading project", MessageBoxButtons.YesNo) == DialogResult.Yes) { service.Documents.CloseAll(vsSaveChanges.vsSaveChangesPrompt); try { Helpers.LogMessage(project.DTE, this, "Updating csproj file"); service.ExecuteCommand("File.SaveAll", string.Empty); service.ExecuteCommand("Project.UnloadProject", string.Empty); MigrateFile(fileName); //project.Imports.AddNewImport(@"C:\Windows\Microsoft.NET\Framework\v3.5\Microsoft.CSharp.targets", null); //project.Save(fileName); service.ExecuteCommand("Project.ReloadProject", string.Empty); } catch { } } }
public void SetProjectTypeGuids(Project proj) { if (Helpers2.IsSharePointVSTemplate(proj.DTE, proj)) { //for VS2010 projects the guid do not need to be added return; } bool reloadRequired = false; string templatesDir = Path.Combine(GetTemplateBasePath(), "Items.Cache"); //Helpers.EnsureGaxPackageRegistration("{14822709-B5A1-4724-98CA-57A101D1B079}", GetPackageGuid(), templatesDir, GetPackageCaption()); Helpers.EnsureGaxPackageRegistration("{349C5853-65DF-11DA-9384-00065B846F21}", "{349C5853-65DF-11DA-9384-00065B846F21}", templatesDir, GetPackageCaption()); string projectTypeGuids = ""; //Microsoft.VisualStudio.Shell.Interop.IVsSolution solution = null; Microsoft.VisualStudio.Shell.Interop.IVsHierarchy hierarchy = null; //Microsoft.VisualStudio.Shell.Interop.IVsAggregatableProject aggregatableProject = null; Microsoft.VisualStudio.Shell.Flavor.IVsAggregatableProjectCorrected aggregatableProject = null; int result = 0; //service = GetService(typeof(Microsoft.VisualStudio.Shell.Interop.IVsSolution)); //solution = (Microsoft.VisualStudio.Shell.Interop.IVsSolution)service; IVsSolution solution = Microsoft.VisualStudio.Shell.Package.GetGlobalService(typeof(SVsSolution)) as IVsSolution; if (solution != null) { result = solution.GetProjectOfUniqueName(proj.UniqueName, out hierarchy); if (result == 0) { //aggregatableProject = (Microsoft.VisualStudio.Shell.Interop.IVsAggregatableProject)hierarchy; aggregatableProject = (Microsoft.VisualStudio.Shell.Flavor.IVsAggregatableProjectCorrected)hierarchy; result = aggregatableProject.GetAggregateProjectTypeGuids(out projectTypeGuids); //csharp if (!projectTypeGuids.ToUpper().Contains("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}")) { if (projectTypeGuids != "") { projectTypeGuids += ";"; } projectTypeGuids += "{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}"; } //wap, warnung: Attach guid before {FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} if (!projectTypeGuids.ToUpper().Contains(String.Intern("{349c5851-65df-11da-9384-00065b846f21}").ToUpper())) { reloadRequired = true; if (projectTypeGuids == "") { projectTypeGuids = "{349c5851-65df-11da-9384-00065b846f21}"; } else { projectTypeGuids = "{349c5851-65df-11da-9384-00065b846f21}" + ";" + projectTypeGuids; } } aggregatableProject.SetAggregateProjectTypeGuids(projectTypeGuids); } } else { Helpers.LogMessage(proj.DTE, this, "Could not add ProjectTypeGuids '{349c5851-65df-11da-9384-00065b846f21};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}' to the project"); } if (reloadRequired) { Project selProj = Helpers.GetSelectedProject(proj.DTE); MessageBox.Show("To enable visual editing of ascx controls the type of the project has been changed." + Environment.NewLine + Environment.NewLine + "The project '" + selProj.Name + "' needs to be reloaded manually ('Unload Project').", "Reload project", MessageBoxButtons.OK, MessageBoxIcon.Warning); Helpers.SelectProject(project); Helpers.LogMessage(project.DTE, this, "Updating csproj file"); proj.DTE.ExecuteCommand("File.SaveAll", string.Empty); proj.DTE.ExecuteCommand("Project.UnloadProject", string.Empty); proj.DTE.ExecuteCommand("Project.ReloadProject", string.Empty); //Project selProj = Helpers.GetSelectedProject(proj.DTE); //Helpers.LogMessage(proj.DTE, this, "selected project " + selProj.Name); /* * Window win = proj.DTE.Windows.Item(EnvDTE.Constants.vsWindowKindCommandWindow); * CommandWindow comwin = (CommandWindow)win.Object; * comwin.SendInput("Project.UnloadProject", true); * comwin.SendInput("Project.ReloadProject", true); * * * proj.DTE.ExecuteCommand("File.SaveAll", string.Empty); * proj.DTE.ExecuteCommand("Project.UnloadProject", string.Empty); * proj.DTE.ExecuteCommand("Project.ReloadProject", string.Empty); */ } }