Beispiel #1
0
		public static BuildResult UpdateDesignerFile (
			CodeBehindWriter writer,
			AspNetAppProject project,
			ProjectFile file, ProjectFile designerFile
		)
		{
			var result = new BuildResult ();

			//parse the ASP.NET file
			var parsedDocument = TypeSystemService.ParseFile (project, file.FilePath) as AspNetParsedDocument;
			if (parsedDocument == null) {
				result.AddError (string.Format ("Failed to parse file '{0}'", file.Name));
				return result;
			}

			//TODO: ensure type system is up to date

			CodeCompileUnit ccu;
			result.Append (GenerateCodeBehind (project, designerFile.FilePath, parsedDocument, out ccu));
			if (ccu != null) {
				writer.WriteFile (designerFile.FilePath, ccu);
			}

			return result;
		}
		static public void Deploy (AspNetAppProject project, ICollection<WebDeployTarget> targets, ConfigurationSelector configuration)
		{
			//project needs to be built before it can be deployed
			IdeApp.ProjectOperations.Build (project);
			
			//set up and launch a copying thread
			DeployThreadParams threadParams = new DeployThreadParams ();
			threadParams.Context = new DeployContext (new WebDeployResolver (), null, null);
			threadParams.Files = MonoDevelop.Deployment.DeployService.GetDeployFiles (threadParams.Context,
			                                                                          project, configuration);
			
			Dictionary<string, string> taskAliases = new Dictionary<string,string> ();
			foreach (WebDeployTarget target in targets) {
				threadParams.Targets.Add ((WebDeployTarget) target.Clone ());
				taskAliases.Add (target.LocationName, target.GetMarkup ());
			}
			
			MultiTaskDialogProgressMonitor monitor = new MultiTaskDialogProgressMonitor (true, true, true, taskAliases);
			monitor.SetDialogTitle (MonoDevelop.Core.GettextCatalog.GetString ("Web Deployment Progress"));
			monitor.SetOperationTitle (MonoDevelop.Core.GettextCatalog.GetString ("Deploying {0}...", project.Name));
			threadParams.Monitor = monitor;
			
			Thread deployThread = new Thread (new ParameterizedThreadStart (DoDeploy));
			deployThread.Name = "Web deploy";
			deployThread.Start (threadParams);
		}
Beispiel #3
0
		public WebDeployWindow (AspNetAppProject project, IList<WebDeployTarget> targets)
		{
			this.Build();
			this.targets = targets;
			this.project = project;
			deployFiles = project.GetDeployFiles ();
		}
		public WebDeployLaunchDialog (AspNetAppProject project)
		{
			this.Build();
			
			this.project = project;
			
			//set up the sort order 
			targetStore.SetSortFunc (LISTCOL_Text, delegate (TreeModel m, TreeIter a, TreeIter b) {
				return string.Compare ((string) m.GetValue (a, LISTCOL_Text), (string) m.GetValue (b, LISTCOL_Text));
			});
			targetStore.SetSortColumnId (LISTCOL_Text, SortType.Ascending);
			
			//set up the view
			targetView.Model = targetStore;
			targetView.HeadersVisible = false;
			
			CellRendererToggle toggleRenderer = new CellRendererToggle ();
			toggleRenderer.Activatable = true;
			toggleRenderer.Xpad = 6;
			TreeViewColumn checkCol = new TreeViewColumn ("", toggleRenderer, "active", LISTCOL_Checked);
			checkCol.Expand = false;
			targetView.AppendColumn (checkCol);
			toggleRenderer.Toggled += HandleToggle;
			
			CellRendererText textRenderer = new CellRendererText ();
			textRenderer.WrapMode = Pango.WrapMode.WordChar;
			targetView.AppendColumn ("", textRenderer, "markup", LISTCOL_Text);
			
			fillStore ();
		}
		public WebTypeContext (AspNetAppProject project)
		{
			if (project == null)
				throw new ArgumentException ("project");
			Project = project;
			SystemWebDom = GetSystemWebDom (project);
			if (Compilation == null)
				throw new InvalidOperationException ("Could not load parse database for project");
		}
Beispiel #6
0
		public static CompletionDataList GetAttributeValues (AspNetAppProject project, FilePath fromFile, string directiveName, string attribute)
		{
			switch (directiveName.ToLowerInvariant ()) {
			case "page":
				return GetPageAttributeValues (project, fromFile, attribute);
			case "register":
				return GetRegisterAttributeValues (project, fromFile, attribute);
			}
			return null;
		}
		public static CompletionDataList CreateProvider (string text, string extension, bool isCtrlSpace)
		{
			string parsedText;
			string editorText;
			int cursorPosition = text.IndexOf ('$');
			int endPos = text.IndexOf ('$', cursorPosition + 1);
			if (endPos == -1)
				parsedText = editorText = text.Substring (0, cursorPosition) + text.Substring (cursorPosition + 1);
			else {
				parsedText = text.Substring (0, cursorPosition) + new string (' ', endPos - cursorPosition) + text.Substring (endPos + 1);
				editorText = text.Substring (0, cursorPosition) + text.Substring (cursorPosition + 1, endPos - cursorPosition - 1) + text.Substring (endPos + 1);
				cursorPosition = endPos - 1; 
			}
			var tww = new MonoDevelop.CSharpBinding.Tests.TestWorkbenchWindow ();
			var sev = new MonoDevelop.CSharpBinding.Tests.TestViewContent ();
			var project = new AspNetAppProject ("C#");
			project.FileName = UnitTests.TestBase.GetTempFile (".csproj");
			
			string file = UnitTests.TestBase.GetTempFile (extension);
			project.AddFile (file);
			
			ProjectDomService.Load (project);
			ProjectDom dom = ProjectDomService.GetProjectDom (project);
			dom.ForceUpdate (true);
			ProjectDomService.Parse (project, file, delegate { return parsedText; });
			ProjectDomService.Parse (project, file, delegate { return parsedText; });
			
			sev.Project = project;
			sev.ContentName = file;
			sev.Text = editorText;
			sev.CursorPosition = cursorPosition;
			tww.ViewContent = sev;
			var doc = new MonoDevelop.Ide.Gui.Document (tww);
			doc.ParsedDocument = new MonoDevelop.AspNet.Parser.AspNetParser ().Parse (null, sev.ContentName, parsedText);
			foreach (var e in doc.ParsedDocument.Errors)
				Console.WriteLine (e);
			
			var textEditorCompletion = new MonoDevelop.AspNet.Gui.AspNetEditorExtension ();
			Initialize (textEditorCompletion, doc);
			
			int triggerWordLength = 1;
			CodeCompletionContext ctx = new CodeCompletionContext ();
			ctx.TriggerOffset = sev.CursorPosition;
			int line, column;
			sev.GetLineColumnFromPosition (sev.CursorPosition, out line, out column);
			ctx.TriggerLine = line;
			ctx.TriggerLineOffset = column - 1;
			
			if (isCtrlSpace)
				return textEditorCompletion.CodeCompletionCommand (ctx) as CompletionDataList;
			else
				return textEditorCompletion.HandleCodeCompletion (ctx, editorText[cursorPosition - 1] , ref triggerWordLength) as CompletionDataList;
		}
		public void Store (AspNetAppProject project)
		{
			XspParameters xPar = project.XspParameters;
			
			xPar.Address = ipAddress.Text;
			xPar.Port = System.Convert.ToUInt16 (portNumber.Value);
			xPar.Verbose = verboseCheck.Active;
			xPar.SslMode = (XspSslMode) sslMode.Active;
			xPar.SslProtocol = (XspSslProtocol) sslProtocol.Active;
			xPar.KeyType = (XspKeyType) keyType.Active;
			xPar.PrivateKeyFile = keyLocation.Path;
			xPar.CertificateFile = certLocation.Path;
			xPar.PasswordOptions = (XspPasswordOptions) passwordOptions.Active;
			xPar.PrivateKeyPassword = passwordEntry.Text;
		}
		public XspOptionsPanelWidget (AspNetAppProject project)
		{
			this.Build();
			
			XspParameters xPar = project.XspParameters;
			
			//index should be equivalent to XspSslMode enum
			((ListStore) sslMode.Model).Clear ();
			sslMode.AppendText (GettextCatalog.GetString ("None"));
			sslMode.AppendText (GettextCatalog.GetString ("Enabled"));
			sslMode.AppendText (GettextCatalog.GetString ("Accept Client Certificates"));
			sslMode.AppendText (GettextCatalog.GetString ("Require Client Certificates"));
			
			//index should be equivalent to XspSslProtocol enum
			((ListStore) sslProtocol.Model).Clear ();
			sslProtocol.AppendText (GettextCatalog.GetString ("Default"));
			sslProtocol.AppendText ("TLS");
			sslProtocol.AppendText ("SSL 2");
			sslProtocol.AppendText ("SSL 3");
			
			((ListStore) keyType.Model).Clear ();
			keyType.AppendText (GettextCatalog.GetString ("None"));
			keyType.AppendText ("Pkcs12");
			keyType.AppendText ("PVK");
			
			((ListStore) passwordOptions.Model).Clear ();
			passwordOptions.AppendText (GettextCatalog.GetString ("None"));
			passwordOptions.AppendText (GettextCatalog.GetString ("Ask"));
			passwordOptions.AppendText (GettextCatalog.GetString ("Store (insecure)"));
			
			//set to valid port range
			portNumber.SetRange (0, UInt16.MaxValue);
			
			//load all options
			ipAddress.Text = xPar.Address;
			portNumber.Value = xPar.Port;
			verboseCheck.Active = xPar.Verbose;
			sslMode.Active = (int) xPar.SslMode;
			sslProtocol.Active = (int) xPar.SslProtocol;
			keyType.Active = (int) xPar.KeyType;
			keyLocation.Path = xPar.PrivateKeyFile;
			certLocation.Path = xPar.CertificateFile;
			passwordOptions.Active = (int) xPar.PasswordOptions;
			passwordEntry.Text = xPar.PrivateKeyPassword;
		}
Beispiel #10
0
		static AspNetTestingEditorExtension CreateEditor (string text, string extension, out string editorText, out TestViewContent sev)
		{
			string parsedText;
			int cursorPosition = text.IndexOf ('$');
			int endPos = text.IndexOf ('$', cursorPosition + 1);
			if (endPos == -1)
				parsedText = editorText = text.Substring (0, cursorPosition) + text.Substring (cursorPosition + 1);
			else {
				parsedText = text.Substring (0, cursorPosition) + new string (' ', endPos - cursorPosition) + text.Substring (endPos + 1);
				editorText = text.Substring (0, cursorPosition) + text.Substring (cursorPosition + 1, endPos - cursorPosition - 1) + text.Substring (endPos + 1);
				cursorPosition = endPos - 1;
			}

			var project = new AspNetAppProject ("C#");
			project.References.Add (new ProjectReference (ReferenceType.Package, "System"));
			project.References.Add (new ProjectReference (ReferenceType.Package, "System.Web"));
			project.FileName = UnitTests.TestBase.GetTempFile (".csproj");
			string file = UnitTests.TestBase.GetTempFile (extension);
			project.AddFile (file);

			var pcw = TypeSystemService.LoadProject (project);
			TypeSystemService.ForceUpdate (pcw);
			pcw.ReconnectAssemblyReferences ();

			sev = new TestViewContent ();
			sev.Project = project;
			sev.ContentName = file;
			sev.Text = editorText;
			sev.CursorPosition = cursorPosition;

			var tww = new TestWorkbenchWindow ();
			tww.ViewContent = sev;

			var doc = new TestDocument (tww);
			doc.Editor.Document.FileName = sev.ContentName;
			var parser = new AspNetParser ();
			var parsedDoc = (AspNetParsedDocument) parser.Parse (false, sev.ContentName, new StringReader (parsedText), project);
			doc.HiddenParsedDocument = parsedDoc;

			return new AspNetTestingEditorExtension (doc);
		}
		public WebDeployOptionsPanelWidget (AspNetAppProject project)
		{
			localCollection = project.WebDeployTargets.Clone ();
			
			//fill model and set it up
			this.Build ();
			foreach (WebDeployTarget target in localCollection) {
				targetList.AppendValues (target.GetMarkup (), target);
			}
			targetView.HeadersVisible = false;
			targetList.SetSortFunc (LISTCOL_TEXT, delegate (TreeModel m, TreeIter a, TreeIter b) {
				return string.Compare ((string) m.GetValue (a, LISTCOL_TEXT), (string) m.GetValue (b, LISTCOL_TEXT));
			});
			targetList.SetSortColumnId (LISTCOL_TEXT, SortType.Ascending);
			
			//set up the view
			targetView.Model = targetList;
			targetView.AppendColumn ("", new Gtk.CellRendererText (), "markup", LISTCOL_TEXT);			
			targetView.Selection.Changed += delegate (object sender, EventArgs e) {
				UpdateButtonState ();
			};
			
			UpdateButtonState ();
		}
Beispiel #12
0
		public static CompletionDataList GetAttributes (AspNetAppProject project, string directiveName,
			Dictionary<string, string> existingAtts)
		{
			var list = new CompletionDataList ();
			bool net20 = project == null || project.TargetFramework.ClrVersion != ClrVersion.Net_1_1;
			
			//FIXME: detect whether the page is VB
			bool vb = false;
			
			switch (directiveName.ToLowerInvariant ()) {
			case "page":
				ExclusiveAdd (list, existingAtts, page11Attributes);
				if (net20)
					ExclusiveAdd (list, existingAtts, page20Attributes);
				if (vb)
					ExclusiveAdd (list, existingAtts, pageVBAttributes);
				MutexAdd (list, existingAtts, page11MutexAttributes);
				break;
				
			case "control":
				ExclusiveAdd (list, existingAtts, userControlAttributes);
				if (vb)
					ExclusiveAdd (list, existingAtts, pageVBAttributes);
				break;
				
			case "master":
				ExclusiveAdd (list, existingAtts, userControlAttributes);
				ExclusiveAdd (list, existingAtts, masterControlAttributes);
				if (vb)
					ExclusiveAdd (list, existingAtts, pageVBAttributes);
				break;
			
			case "mastertype":
				MutexAdd (list, existingAtts, mastertypeAttributes);
				break;
				
			case "assembly":
				//the two assembly directive attributes are mutually exclusive
				MutexAdd (list, existingAtts, assemblyAttributes);
				break;
				
			case "import":
				ExclusiveAdd (list, existingAtts, importAttributes);
				break;
				
			case "reference":
				MutexAdd (list, existingAtts, referenceAttributes);
				break;
				
			case "register":
				ExclusiveAdd (list, existingAtts, registerAttributes);
				if (existingAtts.Keys.Intersect (registerAssemblyAttributes, StringComparer.OrdinalIgnoreCase).Any ()) {
					ExclusiveAdd (list, existingAtts, registerAssemblyAttributes);
				} else if (existingAtts.Keys.Intersect (registerUserControlAttributes, StringComparer.OrdinalIgnoreCase).Any ()) {
					ExclusiveAdd (list, existingAtts, registerUserControlAttributes);
				} else {
					list.AddRange (registerAssemblyAttributes);
					list.AddRange (registerUserControlAttributes);
				}
				break;
				
			case "outputcache":
				ExclusiveAdd (list, existingAtts, outputcacheAttributes);
				break;
				
			case "previouspagetype":
				MutexAdd (list, existingAtts, previousPageTypeAttributes);
				break;
				
			case "implements":
				ExclusiveAdd (list, existingAtts, implementsAttributes);
				break;
			}
			return list.Count > 0? list : null;
		}
Beispiel #13
0
 public DocumentReferenceManager(AspNetAppProject project)
 {
     this.Project = project;
     TypeCtx      = new WebTypeContext(project);
 }
Beispiel #14
0
        public static BuildResult GenerateCodeBehind(
            AspNetAppProject project,
            string filename,
            WebFormsParsedDocument document,
            out CodeCompileUnit ccu)
        {
            ccu = null;
            var    result    = new BuildResult();
            string className = document.Info.InheritedClass;

            AddErrorsToResult(result, filename, document.Errors);
            if (result.ErrorCount > 0)
            {
                return(result);
            }

            if (string.IsNullOrEmpty(className))
            {
                return(result);
            }

            var refman = new WebFormsTypeContext {
                Project = project, Doc = document
            };
            var memberList = new WebFormsMemberListBuilder(refman, document.XDocument);

            memberList.Build();

            AddErrorsToResult(result, filename, memberList.Errors);
            if (result.ErrorCount > 0)
            {
                return(result);
            }

            //initialise the generated type
            ccu = new CodeCompileUnit();
            var namespac = new CodeNamespace();

            ccu.Namespaces.Add(namespac);
            var typeDecl = new CodeTypeDeclaration {
                IsClass   = true,
                IsPartial = true,
            };

            namespac.Types.Add(typeDecl);

            //name the class and namespace
            int namespaceSplit = className.LastIndexOf('.');

            if (namespaceSplit > -1)
            {
                namespac.Name = project.StripImplicitNamespace(className.Substring(0, namespaceSplit));
                typeDecl.Name = className.Substring(namespaceSplit + 1);
            }
            else
            {
                typeDecl.Name = className;
            }

            string masterTypeName = null;

            if (!String.IsNullOrEmpty(document.Info.MasterPageTypeName))
            {
                masterTypeName = document.Info.MasterPageTypeName;
            }
            else if (!String.IsNullOrEmpty(document.Info.MasterPageTypeVPath))
            {
                try {
                    ProjectFile            resolvedMaster       = project.ResolveVirtualPath(document.Info.MasterPageTypeVPath, document.FileName);
                    WebFormsParsedDocument masterParsedDocument = null;
                    if (resolvedMaster != null)
                    {
                        masterParsedDocument = TypeSystemService.ParseFile(project, resolvedMaster.FilePath) as WebFormsParsedDocument;
                    }
                    if (masterParsedDocument != null && !String.IsNullOrEmpty(masterParsedDocument.Info.InheritedClass))
                    {
                        masterTypeName = masterParsedDocument.Info.InheritedClass;
                    }
                } catch (Exception ex) {
                    LoggingService.LogWarning("Error resolving master page type", ex);
                }
                if (string.IsNullOrEmpty(masterTypeName))
                {
                    var msg = string.Format("Could not find type for master '{0}'", document.Info.MasterPageTypeVPath);
                    result.AddError(filename, msg);
                    return(result);
                }
            }

            if (masterTypeName != null)
            {
                var masterProp = new CodeMemberProperty {
                    Name       = "Master",
                    Type       = new CodeTypeReference(masterTypeName),
                    HasGet     = true,
                    HasSet     = false,
                    Attributes = MemberAttributes.Public | MemberAttributes.New | MemberAttributes.Final,
                };
                masterProp.GetStatements.Add(new CodeMethodReturnStatement(
                                                 new CodeCastExpression(masterTypeName,
                                                                        new CodePropertyReferenceExpression(
                                                                            new CodeBaseReferenceExpression(), "Master"))));
                typeDecl.Members.Add(masterProp);
            }

            //shortcut building the existing members type map
            if (memberList.Members.Count == 0)
            {
                return(result);
            }

            var dom     = refman.Compilation;
            var cls     = ReflectionHelper.ParseReflectionName(className).Resolve(dom);
            var members = GetDesignerMembers(memberList.Members.Values, cls, filename);

            //add fields for each control in the page

            foreach (var member in members)
            {
                var type = new CodeTypeReference(member.Type.FullName);
                typeDecl.Members.Add(new CodeMemberField(type, member.Name)
                {
                    Attributes = MemberAttributes.Family
                });
            }
            return(result);
        }
Beispiel #15
0
        static CompletionDataList GetPageAttributeValues(AspNetAppProject project, FilePath fromFile, string attribute)
        {
            var list = new CompletionDataList();

            switch (attribute.ToLowerInvariant())
            {
            //
            //boolean, default to false
            //
            case "async":
            case "aspcompat":
            case "explicit":           // useful for VB only. set to true in machine.config
            case "maintainscrollpositiononpostback":
            case "linepragmas":        //actually not sure if this defaults true or false
            case "smartnavigation":
            case "strict":             //VB ONLY
            case "trace":
                SimpleList.AddBoolean(list, false);
                break;

            //
            //boolean, default to true
            //
            case "autoeventwireup":
            case "buffer":
            case "enableeventvalidation":
            case "enablesessionstate":
            case "enabletheming":
            case "enableviewstate":
            case "enableviewstatemac":
            case "validaterequest":             //enabled in machine.config
            case "debug":
                SimpleList.AddBoolean(list, true);
                break;

            //
            //specialised hard value list completions
            //
            case "codepage":
                list.AddRange(from e in Encoding.GetEncodings() select e.CodePage.ToString());
                list.DefaultCompletionString = Encoding.UTF8.CodePage.ToString();
                break;

            case "compilationmode":
                SimpleList.AddEnum(list, System.Web.UI.CompilationMode.Always);
                break;

            case "culture":
                list.AddRange(from c in CultureInfo.GetCultures(CultureTypes.AllCultures) select c.Name);
                list.DefaultCompletionString = CultureInfo.CurrentCulture.Name;
                break;

            case "lcid":
                //  locale ID, MUTUALLY EXCLUSIVE with Culture
                list.AddRange(from c in CultureInfo.GetCultures(CultureTypes.AllCultures)
                              select c.LCID.ToString());
                list.DefaultCompletionString = CultureInfo.CurrentCulture.LCID.ToString();
                break;

            case "responseencoding":
                list.AddRange(from e in Encoding.GetEncodings() select e.Name);
                list.DefaultCompletionString = Encoding.UTF8.EncodingName;
                break;

            case "tracemode":
                list.Add("SortByTime");
                list.Add("SortByCategory");
                list.DefaultCompletionString = "SortByTime";
                break;

            case "transaction":
                list.Add("Disabled");
                list.Add("NotSupported");
                list.Add("Required");
                list.Add("RequiresNew");
                list.DefaultCompletionString = "Disabled";
                break;

            case "viewstateencryptionmode":
                SimpleList.AddEnum(list, ViewStateEncryptionMode.Auto);
                break;

            case "warninglevel":
                list.AddRange(new string[] { "0", "1", "2", "3", "4" });
                list.DefaultCompletionString = "0";
                break;

            case "masterpagefile":
                return(project != null
                                        ? MonoDevelop.Html.PathCompletion.GetPathCompletion(project, "*.master", fromFile,
                                                                                            x => "~/" + x.ProjectVirtualPath.ToString().Replace(System.IO.Path.PathSeparator, '/'))
                                        : null);

            //
            //we can probably complete these using info from the project, but not yet
            //

            /*
             * case "CodeFile":
             *      //source file to compile for codebehind on server
             * case "ContentType":
             *      //string, HTTP MIME content-type
             * case "CodeFileBaseClass":
             *      // known base class for the partial classes, so code generator knows not
             *      //to redefine fields to ignore members in partial class
             * case "ErrorPage":
             *      // string, URL
             * case "Inherits":
             *      //  IType : Page. defaults to namespace from ClassName
             * case "Language":
             *      //  string, any available .NET language
             * case "Src":
             *      //  string, extra source code for page
             * case "StyleSheetTheme":
             *      //  theme ID, can be overridden by controls
             * case "Theme":
             *      //  theme identifier, overrides controls' themes
             * case "UICulture":
             *      //  string, valid UI culture
             */

            //
            //we're not likely to suggest anything for these:
            //

            /*
             * case "AsyncTimeOut":
             *      // int in seconds, default 45
             * case "ClassName":
             *      //string, .NET name, default namespace ASP
             * case "ClientTarget":
             *      //string, user agent
             * case "CodeBehind":
             *      //valid but IGNORE. VS-only
             * case "CompilerOptions":
             *      //string, list of compiler switches
             * case "Description":
             *      // string, pointless
             * case "TargetSchema":
             *      //  schema to validate page content. IGNORED, so rather pointless
             * case "Title":
             *      //  string for <title>
             */
            default:
                return(null);
            }

            return(list.Count > 0? list : null);
        }
        public override void ApplyChanges()
        {
            AspNetAppProject project = (AspNetAppProject)ConfiguredProject;

            panel.Store(project);
        }
		public WebFormReferenceManager (AspNetAppProject project) : base (project)
		{
		}
		static public void Deploy (AspNetAppProject project, WebDeployTarget target, ConfigurationSelector configuration)
		{
			Deploy (project, new WebDeployTarget[] { target }, configuration);
		}
Beispiel #19
0
        public override void ModifyTags(SolutionItem policyParent, Project project, string language, string identifier, string fileName, ref Dictionary <string, string> tags)
        {
            base.ModifyTags(policyParent, project, language, identifier, fileName, ref tags);
            if (fileName == null)
            {
                return;
            }

            tags ["AspNetMaster"]        = "";
            tags ["AspNetMasterContent"] = "";

            AspNetAppProject aspProj = project as AspNetAppProject;

            if (aspProj == null)
            {
                throw new InvalidOperationException("MasterContentFileDescriptionTemplate is only valid for ASP.NET projects");
            }

            ProjectFile masterPage = null;

            var dialog = new MonoDevelop.Ide.Projects.ProjectFileSelectorDialog(aspProj, null, "*.master");

            try {
                dialog.Title = GettextCatalog.GetString("Select a Master Page...");
                int response = MonoDevelop.Ide.MessageService.RunCustomDialog(dialog);
                if (response == (int)Gtk.ResponseType.Ok)
                {
                    masterPage = dialog.SelectedFile;
                }
            } finally {
                dialog.Destroy();
            }
            if (masterPage == null)
            {
                return;
            }

            tags ["AspNetMaster"] = aspProj.LocalToVirtualPath(masterPage);

            try {
                var pd = TypeSystemService.ParseFile(project, masterPage.FilePath)
                         as WebFormsParsedDocument;
                if (pd == null)
                {
                    return;
                }

                var sb = new System.Text.StringBuilder();
                foreach (string id in pd.XDocument.GetAllPlaceholderIds())
                {
                    sb.Append("<asp:Content ContentPlaceHolderID=\"");
                    sb.Append(id);
                    sb.Append("\" ID=\"");
                    sb.Append(id);
                    sb.Append("Content\" runat=\"server\">\n</asp:Content>\n");
                }

                tags["AspNetMasterContent"] = sb.ToString();
            }
            catch (Exception ex) {
                //no big loss if we just insert blank space
                //it's just a template for the user to start editing
                LoggingService.LogWarning("Error generating AspNetMasterContent for template", ex);
            }
        }
 static public void Deploy(AspNetAppProject project, WebDeployTarget target, ConfigurationSelector configuration)
 {
     Deploy(project, new WebDeployTarget[] { target }, configuration);
 }
Beispiel #21
0
		public static BuildResult GenerateCodeBehind (
			AspNetAppProject project,
			string filename,
			AspNetParsedDocument document,
			out CodeCompileUnit ccu)
		{
			ccu = null;
			var result = new BuildResult ();
			string className = document.Info.InheritedClass;

			foreach (var err in document.Errors)
				result.AddError (filename, err.Region.BeginLine, err.Region.BeginColumn, null, err.Message);
			if (result.ErrorCount > 0)
				return result;
			
			if (string.IsNullOrEmpty (className))
				return result;
			
			var refman = new DocumentReferenceManager (project) { Doc = document };
			var memberList = new MemberListBuilder (refman, document.XDocument);
			memberList.Build ();

			foreach (var err in memberList.Errors)
				result.AddError (filename, err.Region.BeginLine, err.Region.BeginColumn, null, err.Message);
			if (result.ErrorCount > 0)
				return result;
			
			//initialise the generated type
			ccu = new CodeCompileUnit ();
			var namespac = new CodeNamespace ();
			ccu.Namespaces.Add (namespac); 
			var typeDecl = new CodeTypeDeclaration {
				IsClass = true,
				IsPartial = true,
			};
			namespac.Types.Add (typeDecl);
			
			//name the class and namespace
			int namespaceSplit = className.LastIndexOf ('.');
			if (namespaceSplit > -1) {
				namespac.Name = project.StripImplicitNamespace (className.Substring (0, namespaceSplit));
				typeDecl.Name = className.Substring (namespaceSplit + 1);
			} else {
				typeDecl.Name = className;
			}
			
			string masterTypeName = null;
			if (!String.IsNullOrEmpty (document.Info.MasterPageTypeName)) {
				masterTypeName = document.Info.MasterPageTypeName;
			} else if (!String.IsNullOrEmpty (document.Info.MasterPageTypeVPath)) {
				try {
					ProjectFile resolvedMaster = project.ResolveVirtualPath (document.Info.MasterPageTypeVPath, document.FileName);
					AspNetParsedDocument masterParsedDocument = null;
					if (resolvedMaster != null)
						masterParsedDocument = TypeSystemService.ParseFile (project, resolvedMaster.FilePath) as AspNetParsedDocument;
					if (masterParsedDocument != null && !String.IsNullOrEmpty (masterParsedDocument.Info.InheritedClass))
						masterTypeName = masterParsedDocument.Info.InheritedClass;
				} catch (Exception ex) {
					LoggingService.LogWarning ("Error resolving master page type", ex);
				}
				if (string.IsNullOrEmpty (masterTypeName)) {
					var msg = string.Format ("Could not find type for master '{0}'", document.Info.MasterPageTypeVPath);
					result.AddError (filename, msg);
					return result;
				}
			}
			
			if (masterTypeName != null) {
				var masterProp = new CodeMemberProperty {
					Name = "Master",
					Type = new CodeTypeReference (masterTypeName),
					HasGet = true,
					HasSet = false,
					Attributes = MemberAttributes.Public | MemberAttributes.New | MemberAttributes.Final,
				};
				masterProp.GetStatements.Add (new CodeMethodReturnStatement (
						new CodeCastExpression (masterTypeName, 
							new CodePropertyReferenceExpression (
								new CodeBaseReferenceExpression (), "Master"))));
				typeDecl.Members.Add (masterProp);
			}
			
			//shortcut building the existing members type map
			if (memberList.Members.Count == 0)
				return result;
			
			var dom = refman.TypeCtx.Compilation;
			var cls = ReflectionHelper.ParseReflectionName (className).Resolve (dom);
			var members = GetDesignerMembers (memberList.Members.Values, cls, filename);
			
			//add fields for each control in the page
			
			foreach (var member in members) {
				var type = new CodeTypeReference (member.Type.FullName);
				typeDecl.Members.Add (new CodeMemberField (type, member.Name) { Attributes = MemberAttributes.Family });
			}
			return result;
		}
Beispiel #22
0
		static CompletionDataList GetPageAttributeValues (AspNetAppProject project, FilePath fromFile, string attribute)
		{
			var list = new CompletionDataList ();
			switch (attribute.ToLowerInvariant ()) {
			
			//
			//boolean, default to false
			//
			case "async":
			case "aspcompat":
			case "explicit": // useful for VB only. set to true in machine.config
			case "maintainscrollpositiononpostback":
			case "linepragmas": //actually not sure if this defaults true or false
			case "smartnavigation":
			case "strict": //VB ONLY 
			case "trace":
				SimpleList.AddBoolean (list, false);
				break;
			
			//
			//boolean, default to true
			//
			case "autoeventwireup":
			case "buffer":	
			case "enableeventvalidation":
			case "enablesessionstate":
			case "enabletheming":
			case "enableviewstate":
			case "enableviewstatemac":
			case "validaterequest": //enabled in machine.config
			case "debug":
				SimpleList.AddBoolean (list, true);
				break;
			
			//
			//specialised hard value list completions
			//
			case "codepage":
				list.AddRange (from e in Encoding.GetEncodings () select e.CodePage.ToString ());
				list.DefaultCompletionString = Encoding.UTF8.CodePage.ToString ();
				break;
				
			case "compilationmode":
				SimpleList.AddEnum (list, System.Web.UI.CompilationMode.Always);
				break;
				
			case "culture":
				list.AddRange (from c in CultureInfo.GetCultures (CultureTypes.AllCultures) select c.Name);
				list.DefaultCompletionString = CultureInfo.CurrentCulture.Name;
				break;
			
			case "lcid":
				//  locale ID, MUTUALLY EXCLUSIVE with Culture
				list.AddRange (from c in CultureInfo.GetCultures (CultureTypes.AllCultures)
				               select c.LCID.ToString ());
				list.DefaultCompletionString = CultureInfo.CurrentCulture.LCID.ToString ();
				break;
			
			case "responseencoding":
				list.AddRange (from e in Encoding.GetEncodings () select e.Name);
				list.DefaultCompletionString = Encoding.UTF8.EncodingName;
				break;
			
			case "tracemode":
				list.Add ("SortByTime");
				list.Add ("SortByCategory");
				list.DefaultCompletionString = "SortByTime";
				break;
			
			case "transaction":
				list.Add ("Disabled");
				list.Add ("NotSupported");
				list.Add ("Required");
				list.Add ("RequiresNew");
				list.DefaultCompletionString = "Disabled";
				break;
			
			case "viewstateencryptionmode":
				SimpleList.AddEnum (list, ViewStateEncryptionMode.Auto);
				break;
				
			case "warninglevel":
				list.AddRange (new string[] {"0", "1", "2", "3", "4"});
				list.DefaultCompletionString = "0";
				break;
				
			case "masterpagefile":
				return project != null
					? MonoDevelop.Html.PathCompletion.GetPathCompletion (project, "*.master", fromFile,
						x => "~/" + x.ProjectVirtualPath.ToString ().Replace (System.IO.Path.PathSeparator, '/')) 
					: null;
			
			//
			//we can probably complete these using info from the project, but not yet
			//
			/*
			case "CodeFile":
				//source file to compile for codebehind on server	
			case "ContentType":
				//string, HTTP MIME content-type
			case "CodeFileBaseClass":
				// known base class for the partial classes, so code generator knows not 
				//to redefine fields to ignore members in partial class	
			case "ErrorPage":
				// string, URL
			case "Inherits":
				//  IType : Page. defaults to namespace from ClassName 
			case "Language":
				//  string, any available .NET language
			case "Src":
				//  string, extra source code for page
			case "StyleSheetTheme":
				//  theme ID, can be overridden by controls
			case "Theme":
				//  theme identifier, overrides controls' themes
			case "UICulture":
				//  string, valid UI culture	
			*/
			
			//
			//we're not likely to suggest anything for these:
			//
			/*
			case "AsyncTimeOut":
				// int in seconds, default 45
			case "ClassName":
				//string, .NET name, default namespace ASP
			case "ClientTarget":
				//string, user agent
			case "CodeBehind":
				//valid but IGNORE. VS-only
			case "CompilerOptions":
				//string, list of compiler switches
			case "Description":
				// string, pointless
			case "TargetSchema":
				//  schema to validate page content. IGNORED, so rather pointless
			case "Title":
				//  string for <title>
			*/	
			default:
				return null;
			}
			
			return list.Count > 0? list : null;
		}
Beispiel #23
0
		static CompletionDataList GetRegisterAttributeValues (AspNetAppProject project, FilePath fromFile, string attribute)
		{
			switch (attribute.ToLowerInvariant ()) {
			case "src":
				return project != null
					? MonoDevelop.Html.PathCompletion.GetPathCompletion (project, "*.ascx", fromFile,
						x => "~/" + x.ProjectVirtualPath.ToString ().Replace (System.IO.Path.PathSeparator, '/')) 
					: null;
			}
			return null;
		}	
		public static IEnumerable<IType> ListSystemControlClasses (IType baseType, AspNetAppProject project)
		{
			return ListControlClasses (baseType, GetSystemWebDom (project), "System.Web.UI.WebControls");
		}
Beispiel #25
0
        public static CompletionDataList CreateProvider(string text, string extension, bool isCtrlSpace)
        {
            string parsedText;
            string editorText;
            int    cursorPosition = text.IndexOf('$');
            int    endPos         = text.IndexOf('$', cursorPosition + 1);

            if (endPos == -1)
            {
                parsedText = editorText = text.Substring(0, cursorPosition) + text.Substring(cursorPosition + 1);
            }
            else
            {
                parsedText     = text.Substring(0, cursorPosition) + new string (' ', endPos - cursorPosition) + text.Substring(endPos + 1);
                editorText     = text.Substring(0, cursorPosition) + text.Substring(cursorPosition + 1, endPos - cursorPosition - 1) + text.Substring(endPos + 1);
                cursorPosition = endPos - 1;
            }
            var tww     = new MonoDevelop.CSharpBinding.Tests.TestWorkbenchWindow();
            var sev     = new MonoDevelop.CSharpBinding.Tests.TestViewContent();
            var project = new AspNetAppProject("C#");

            project.FileName = UnitTests.TestBase.GetTempFile(".csproj");

            string file = UnitTests.TestBase.GetTempFile(extension);

            project.AddFile(file);

            ProjectDomService.Load(project);
            ProjectDom dom = ProjectDomService.GetProjectDom(project);

            dom.ForceUpdate(true);
            ProjectDomService.Parse(project, file, delegate
            {
                return(parsedText);
            });
            ProjectDomService.Parse(project, file, delegate
            {
                return(parsedText);
            });

            sev.Project        = project;
            sev.ContentName    = file;
            sev.Text           = editorText;
            sev.CursorPosition = cursorPosition;
            tww.ViewContent    = sev;
            var doc = new MonoDevelop.Ide.Gui.Document(tww);

            doc.ParsedDocument = new MonoDevelop.AspNet.Parser.AspNetParser().Parse(null, sev.ContentName, parsedText);
            foreach (var e in doc.ParsedDocument.Errors)
            {
                Console.WriteLine(e);
            }

            var textEditorCompletion = new MonoDevelop.AspNet.Gui.AspNetEditorExtension();

            Initialize(textEditorCompletion, doc);

            int triggerWordLength     = 1;
            CodeCompletionContext ctx = new CodeCompletionContext();

            ctx.TriggerOffset = sev.CursorPosition;
            int line, column;

            sev.GetLineColumnFromPosition(sev.CursorPosition, out line, out column);
            ctx.TriggerLine       = line;
            ctx.TriggerLineOffset = column - 1;

            if (isCtrlSpace)
            {
                return(textEditorCompletion.CodeCompletionCommand(ctx) as CompletionDataList);
            }
            else
            {
                return(textEditorCompletion.HandleCodeCompletion(ctx, editorText[cursorPosition - 1], ref triggerWordLength) as CompletionDataList);
            }
        }
		//FIXME: this shouldn't be public
		public static ICompilation GetSystemWebDom (AspNetAppProject project)
		{
			return GetSystemWebDom (project.TargetRuntime, project.TargetFramework);
		}
 public WebFormReferenceManager(AspNetAppProject project) : base(project)
 {
 }
		public static System.CodeDom.CodeCompileUnit GenerateCodeBehind (AspNetAppProject project,
		                                                                 string filename,
		                                                                 AspNetParsedDocument document, 
		                                                                 List<CodeBehindWarning> errors)
		{
			string className = document.Info.InheritedClass;
			
			if (document.HasErrors) {
				AddFail (errors, document, document.Errors.Where (x => x.ErrorType == ErrorType.Error).First ());
				return null;
			}
			
			if (string.IsNullOrEmpty (className))
				return null;
			
			var refman = new DocumentReferenceManager (project) { Doc = document };
			var memberList = new MemberListVisitor (document, refman);
			document.RootNode.AcceptVisit (memberList);
			
			var err = memberList.Errors.Where (x => x.ErrorType == ErrorType.Error).FirstOrDefault ();
			if (err != null) {
				AddFail (errors, document, err);
				return null;
			}
			
			//initialise the generated type
			var ccu = new CodeCompileUnit ();
			var namespac = new CodeNamespace ();
			ccu.Namespaces.Add (namespac); 
			var typeDecl = new System.CodeDom.CodeTypeDeclaration () {
				IsClass = true,
				IsPartial = true,
			};
			namespac.Types.Add (typeDecl);
			
			//name the class and namespace
			int namespaceSplit = className.LastIndexOf ('.');
			string namespaceName = null;
			if (namespaceSplit > -1) {
				namespac.Name = project.StripImplicitNamespace (className.Substring (0, namespaceSplit));
				typeDecl.Name = className.Substring (namespaceSplit + 1);
			} else {
				typeDecl.Name = className;
			}
			
			string masterTypeName = null;
			if (!String.IsNullOrEmpty (document.Info.MasterPageTypeName)) {
				masterTypeName = document.Info.MasterPageTypeName;
			} else if (!String.IsNullOrEmpty (document.Info.MasterPageTypeVPath)) {
				try {
					ProjectFile resolvedMaster = project.ResolveVirtualPath (document.Info.MasterPageTypeVPath, document.FileName);
					AspNetParsedDocument masterParsedDocument = null;
					if (resolvedMaster != null)
						masterParsedDocument = ProjectDomService.Parse (project, resolvedMaster.FilePath, null)	as AspNetParsedDocument;
					if (masterParsedDocument != null && !String.IsNullOrEmpty (masterParsedDocument.Info.InheritedClass)) {
						masterTypeName = masterParsedDocument.Info.InheritedClass;
					} else {
						errors.Add (new CodeBehindWarning (String.Format ("Could not find type for master '{0}'",
						                                                  document.Info.MasterPageTypeVPath),
						                                   document.FileName));
					}
				} catch (Exception ex) {
					errors.Add (new CodeBehindWarning (String.Format ("Could not find type for master '{0}'",
					                                                  document.Info.MasterPageTypeVPath),
					                                   document.FileName));
					LoggingService.LogWarning ("Error resolving master page type", ex);
				}
			}
			
			if (masterTypeName != null) {
				var masterProp = new CodeMemberProperty () {
					Name = "Master",
					Type = new CodeTypeReference (masterTypeName),
					HasGet = true,
					HasSet = false,
					Attributes = System.CodeDom.MemberAttributes.Public | System.CodeDom.MemberAttributes.New 
						| System.CodeDom.MemberAttributes.Final,
				};
				masterProp.GetStatements.Add (new System.CodeDom.CodeMethodReturnStatement (
						new System.CodeDom.CodeCastExpression (masterTypeName, 
							new System.CodeDom.CodePropertyReferenceExpression (
								new System.CodeDom.CodeBaseReferenceExpression (), "Master"))));
				typeDecl.Members.Add (masterProp);
			}
			
			//shortcut building the existing members type map
			if (memberList.Members.Count == 0)
				return ccu;
			
			var dom = refman.TypeCtx.ProjectDom;
			var cls = dom.GetType (className);
			var members = GetDesignerMembers (memberList.Members.Values, cls, filename, dom, dom);
			
			//add fields for each control in the page
			
			foreach (var member in members) {
				var type = new CodeTypeReference (member.Type.FullName);
				typeDecl.Members.Add (new CodeMemberField (type, member.Name) { Attributes = MemberAttributes.Family });
			}
			return ccu;
		}
        public static void AddController(AspNetAppProject project, string path, string name)
        {
            var provider = project.LanguageBinding.GetCodeDomProvider();

            if (provider == null)
            {
                throw new InvalidOperationException("Project language has null CodeDOM provider");
            }

            string outputFile          = null;
            MvcTextTemplateHost host   = null;
            AddControllerDialog dialog = null;

            try {
                dialog = new AddControllerDialog(project);
                if (!String.IsNullOrEmpty(name))
                {
                    dialog.ControllerName = name;
                }

                bool fileGood = false;
                while (!fileGood)
                {
                    var resp = (Gtk.ResponseType)MessageService.RunCustomDialog(dialog);
                    dialog.Hide();
                    if (resp != Gtk.ResponseType.Ok || !dialog.IsValid())
                    {
                        return;
                    }

                    outputFile = System.IO.Path.Combine(path, dialog.ControllerName) + ".cs";

                    if (System.IO.File.Exists(outputFile))
                    {
                        fileGood = MessageService.AskQuestion("Overwrite file?",
                                                              String.Format("The file '{0}' already exists.\n", dialog.ControllerName) +
                                                              "Would you like to overwrite it?", AlertButton.OverwriteFile, AlertButton.Cancel)
                                   != AlertButton.Cancel;
                    }
                    else
                    {
                        break;
                    }
                }

                host = new MvcTextTemplateHost {
                    LanguageExtension = provider.FileExtension,
                    ItemName          = dialog.ControllerName,
                    NameSpace         = project.DefaultNamespace + ".Controllers"
                };

                host.ProcessTemplate(dialog.TemplateFile, outputFile);
                MonoDevelop.TextTemplating.TextTemplatingService.ShowTemplateHostErrors(host.Errors);
            } finally {
                if (host != null)
                {
                    host.Dispose();
                }
                if (dialog != null)
                {
                    dialog.Destroy();
                }
            }

            if (System.IO.File.Exists(outputFile))
            {
                project.AddFile(outputFile);
                IdeApp.ProjectOperations.Save(project);
            }
        }
		static public void DeployDialog (AspNetAppProject project)
		{
			var dialog = new WebDeployLaunchDialog (project) {
				Modal = true,
			};
			dialog.Show ();
			
			ICollection<WebDeployTarget> targets = null;
			
			var response = ResponseType.None;
			do {
				response = (ResponseType) MessageService.RunCustomDialog (dialog, MessageService.RootWindow);
			} while (response != ResponseType.Ok && response != ResponseType.Cancel && response != ResponseType.DeleteEvent);
			
			if (response == Gtk.ResponseType.Ok)
				targets = dialog.GetSelectedTargets ();
			
			dialog.Destroy ();
			
			if (targets != null && targets.Count > 0)
				Deploy (project, targets, IdeApp.Workspace.ActiveConfiguration);
		}
		public DocumentReferenceManager (AspNetAppProject project)
		{
			this.Project = project;
			TypeCtx = new WebTypeContext (project);
		}
        protected override void Run()
        {
            AspNetAppProject project = (AspNetAppProject)IdeApp.ProjectOperations.CurrentSelectedProject;

            WebDeployService.DeployDialog(project);
        }
Beispiel #33
0
        public static CompletionDataList GetAttributes(AspNetAppProject project, string directiveName,
                                                       Dictionary <string, string> existingAtts)
        {
            var  list  = new CompletionDataList();
            bool net20 = project == null || project.TargetFramework.ClrVersion != ClrVersion.Net_1_1;

            //FIXME: detect whether the page is VB
            bool vb = false;

            switch (directiveName.ToLowerInvariant())
            {
            case "page":
                ExclusiveAdd(list, existingAtts, page11Attributes);
                if (net20)
                {
                    ExclusiveAdd(list, existingAtts, page20Attributes);
                }
                if (vb)
                {
                    ExclusiveAdd(list, existingAtts, pageVBAttributes);
                }
                MutexAdd(list, existingAtts, page11MutexAttributes);
                break;

            case "control":
                ExclusiveAdd(list, existingAtts, userControlAttributes);
                if (vb)
                {
                    ExclusiveAdd(list, existingAtts, pageVBAttributes);
                }
                break;

            case "master":
                ExclusiveAdd(list, existingAtts, userControlAttributes);
                ExclusiveAdd(list, existingAtts, masterControlAttributes);
                if (vb)
                {
                    ExclusiveAdd(list, existingAtts, pageVBAttributes);
                }
                break;

            case "mastertype":
                MutexAdd(list, existingAtts, mastertypeAttributes);
                break;

            case "assembly":
                //the two assembly directive attributes are mutually exclusive
                MutexAdd(list, existingAtts, assemblyAttributes);
                break;

            case "import":
                ExclusiveAdd(list, existingAtts, importAttributes);
                break;

            case "reference":
                MutexAdd(list, existingAtts, referenceAttributes);
                break;

            case "register":
                ExclusiveAdd(list, existingAtts, registerAttributes);
                if (existingAtts.Keys.Intersect(registerAssemblyAttributes, StringComparer.OrdinalIgnoreCase).Any())
                {
                    ExclusiveAdd(list, existingAtts, registerAssemblyAttributes);
                }
                else if (existingAtts.Keys.Intersect(registerUserControlAttributes, StringComparer.OrdinalIgnoreCase).Any())
                {
                    ExclusiveAdd(list, existingAtts, registerUserControlAttributes);
                }
                else
                {
                    list.AddRange(registerAssemblyAttributes);
                    list.AddRange(registerUserControlAttributes);
                }
                break;

            case "outputcache":
                ExclusiveAdd(list, existingAtts, outputcacheAttributes);
                break;

            case "previouspagetype":
                MutexAdd(list, existingAtts, previousPageTypeAttributes);
                break;

            case "implements":
                ExclusiveAdd(list, existingAtts, implementsAttributes);
                break;
            }
            return(list.Count > 0? list : null);
        }
		public void Store (AspNetAppProject project)
		{
			project.WebDeployTargets.Clear ();
			foreach (WebDeployTarget target in localCollection)
				project.WebDeployTargets.Add ((WebDeployTarget) target.Clone ());
		}
        public override Widget CreatePanelWidget()
        {
            AspNetAppProject project = (AspNetAppProject)ConfiguredProject;

            return(panel = new WebDeployOptionsPanelWidget(project));
        }