public override void ModifyTags(MonoDevelop.Projects.SolutionItem policyParent, MonoDevelop.Projects.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 AspNetParsedDocument;
                if (pd == null)
                {
                    return;
                }

                var visitor = new ContentPlaceHolderVisitor();
                pd.RootNode.AcceptVisit(visitor);

                var sb = new System.Text.StringBuilder();
                foreach (string id in visitor.PlaceHolders)
                {
                    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);
            }
        }
Example #2
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;

            AddErrorsToResult(result, filename, document.Errors);
            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();

            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);
                    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);
        }
Example #3
0
        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) 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);
        }
Example #4
0
 //FIXME: this shouldn't be public
 public static ICompilation GetSystemWebDom(AspNetAppProject project)
 {
     return(GetSystemWebDom(project.TargetRuntime, project.TargetFramework));
 }
Example #5
0
 public static IEnumerable <IType> ListSystemControlClasses(IType baseType, AspNetAppProject project)
 {
     return(ListControlClasses(baseType, GetSystemWebDom(project), "System.Web.UI.WebControls"));
 }
Example #6
0
        protected override BuildResult Build(IProgressMonitor monitor, SolutionEntityItem project, ConfigurationSelector configuration)
        {
            AspNetAppProject aspProject = project as AspNetAppProject;

            //get the config object and validate
            AspNetAppProjectConfiguration config = (AspNetAppProjectConfiguration)aspProject.GetConfiguration(configuration);

            if (config == null)
            {
                monitor.Log.WriteLine(GettextCatalog.GetString
                                          ("Project configuration is invalid. Skipping CodeBehind member generation."));
                return(base.Build(monitor, project, configuration));
            }

            if (config.DisableCodeBehindGeneration)
            {
                monitor.Log.WriteLine(GettextCatalog.GetString
                                          ("Skipping updating of CodeBehind partial classes, because this feature is disabled."));
                return(base.Build(monitor, project, configuration));
            }

            CodeBehindWriter writer = CodeBehindWriter.CreateForProject(monitor, aspProject);

            if (!writer.SupportsPartialTypes)
            {
                monitor.Log.WriteLine(GettextCatalog.GetString
                                          ("The code generator for {0} does not support partial classes. Skipping CodeBehind member generation.",
                                          aspProject.LanguageBinding.Language));;
                return(base.Build(monitor, project, configuration));
            }

            //get the extension used for codebehind files
            string langExt = aspProject.LanguageBinding.GetFileName("a");

            langExt = langExt.Substring(1, langExt.Length - 1);

            List <CodeBehindWarning> errors = new List <CodeBehindWarning> ();

            monitor.Log.WriteLine(GettextCatalog.GetString("Generating CodeBehind members..."));

            bool updatedParseDb = false;

            //go over all the files generating members where necessary
            foreach (ProjectFile file in aspProject.Files)
            {
                WebSubtype type = AspNetAppProject.DetermineWebSubtype(file.FilePath);
                if (type != WebSubtype.WebForm && type != WebSubtype.WebControl && type != WebSubtype.MasterPage)
                {
                    continue;
                }

                //find the designer file
                ProjectFile designerFile = aspProject.Files.GetFile(file.Name + ".designer" + langExt);
                if (designerFile == null)
                {
                    aspProject.Files.GetFile(file.Name + ".Designer" + langExt);
                }
                if (designerFile == null)
                {
                    continue;
                }

                //only regenerate the designer class if it's older than the aspx (etc) file
                if (System.IO.File.GetLastWriteTimeUtc(designerFile.FilePath)
                    > System.IO.File.GetLastWriteTimeUtc(file.FilePath))
                {
                    continue;
                }

                //need parse DB to be up to date
                if (!updatedParseDb)
                {
                    updatedParseDb = true;
                    monitor.Log.Write(GettextCatalog.GetString("Waiting for project type database to finish updating..."));
                    ProjectDom dom = ProjectDomService.GetProjectDom(aspProject);
                    dom.ForceUpdate(true);
                    monitor.Log.WriteLine(GettextCatalog.GetString(" complete."));
                }

                //parse the ASP.NET file
                var parsedDocument = ProjectDomService.Parse(aspProject, file.FilePath) as AspNetParsedDocument;
                if (parsedDocument == null)
                {
                    continue;
                }

                var ccu = CodeBehind.GenerateCodeBehind(aspProject, designerFile.FilePath, parsedDocument, errors);
                if (ccu == null)
                {
                    continue;
                }

                writer.Write(ccu, designerFile.FilePath);
            }

            writer.WriteOpenFiles();

            //write out a friendly message aout what we did
            if (writer.WrittenCount > 0)
            {
                monitor.Log.WriteLine(GettextCatalog.GetString("{0} CodeBehind designer classes updated.", writer.WrittenCount));
            }
            else
            {
                monitor.Log.WriteLine(GettextCatalog.GetString("No changes made to CodeBehind classes."));
            }

            //and construct and return a build result
            BuildResult baseResult = base.Build(monitor, project, configuration);

            foreach (CodeBehindWarning cbw in errors)
            {
                if (cbw.FileName != null)
                {
                    baseResult.AddWarning(cbw.FileName, cbw.Line, cbw.Column, null, cbw.WarningText);
                }
                else
                {
                    baseResult.AddWarning(cbw.WarningText);
                }
            }
            return(baseResult);
        }
Example #7
0
        public override bool SupportsItem(IBuildTarget item)
        {
            AspNetAppProject aspProject = item as AspNetAppProject;

            return(aspProject != null && aspProject.LanguageBinding != null);
        }