/// <summary>
        /// Parse the text of the given designer file into a series of property declarations and return them.
        /// This uses simple line-by-line parsing, not a proper code parse, because Visual Studio does the same
        /// thing, and a .designer file is only considered valid if Visual Studio can read it.
        /// </summary>
        /// <param name="compileContext">The context in which to report errors during the parse.</param>
        /// <param name="designerText">The text of the designer file to parse.</param>
        /// <returns>The results of reading and parsing the designer file.</returns>
        public DesignerInfo ParseDesignerText(ICompileContext compileContext, string designerText)
        {
            _compileContext = compileContext;
            _line           = 0;

            Verbose("Beginning parse of .designer file.");

            string[] lines = _lineSplitter.Split(designerText);

            Verbose("{0} lines of text found in .designer file.", lines.Length);

            DesignerInfo designerInfo = new DesignerInfo();

            ParsingState state = ParsingState.BeforeNamespace;

            for (_line = 1; _line <= lines.Length; _line++)
            {
                string currentLine = lines[_line - 1];

                // Skip blank lines and comment lines.
                if (_isBlankOrComment.IsMatch(currentLine))
                {
                    continue;
                }

                // We use a simple finite-state machine to perform the parsing.  It transitions on declarations and curly braces.
                switch (state)
                {
                case ParsingState.BeforeNamespace:
                {
                    Match match;
                    if ((match = _isNamespaceDeclaration.Match(currentLine)).Success)
                    {
                        if (string.IsNullOrEmpty(match.Groups["curlybrace"].Value))
                        {
                            Error("There is a valid namespace declaration here, but the opening curly brace is not on the same line.  Visual Studio is strict about curly-brace placement, and probably cannot read this .designer file.");
                        }
                        else
                        {
                            designerInfo.Namespace = match.Groups["namespace"].Value;
                            Verbose("Parsed a valid namespace declaration for namespace \"{0}\".", designerInfo.Namespace);
                            state = ParsingState.BeforeClass;
                        }
                    }
                    else
                    {
                        Error("There should be a valid namespace declaration here.  Visual Studio probably cannot read this .designer file.");
                    }
                }
                break;

                case ParsingState.BeforeClass:
                {
                    Match match;
                    if ((match = _isClassDeclaration.Match(currentLine)).Success)
                    {
                        if (string.IsNullOrEmpty(match.Groups["curlybrace"].Value))
                        {
                            Error("There is a valid class declaration here, but the opening curly brace is not on the same line.  Visual Studio is strict about curly-brace placement, and probably cannot read this .designer file.");
                        }
                        else
                        {
                            designerInfo.ClassName = match.Groups["classname"].Value;
                            Verbose("Parsed a valid class declaration for class \"{0}\".", designerInfo.ClassName);
                            state = ParsingState.InsideClass;
                        }
                    }
                    else
                    {
                        Error("There should be a valid partial class declaration here.  Visual Studio probably cannot read this .designer file.");
                    }
                }
                break;

                case ParsingState.InsideClass:
                {
                    Match match;
                    if (_isClosedCurlyBrace.IsMatch(currentLine))
                    {
                        state = ParsingState.AfterClass;
                        Verbose("End of class.");
                    }
                    else if ((match = _isPropertyDeclaration.Match(currentLine)).Success)
                    {
                        DesignerPropertyDeclaration propertyDeclaration = new DesignerPropertyDeclaration
                        {
                            PropertyTypeName = match.Groups["typename"].Value,
                            Name             = match.Groups["propertyname"].Value,
                        };
                        designerInfo.PropertyDeclarations.Add(propertyDeclaration);

                        Verbose("Found property declaration: {0} {1}", propertyDeclaration.PropertyTypeName, propertyDeclaration.Name);
                    }
                    else
                    {
                        Warning("There should be a protected property declaration here.  Visual Studio may not be able to read this .designer file.");
                    }
                }
                break;

                case ParsingState.AfterClass:
                    if (_isClosedCurlyBrace.IsMatch(currentLine))
                    {
                        state = ParsingState.AfterNamespace;
                        Verbose("End of namespace.");
                    }
                    else
                    {
                        Error("There should be a closing curly brace here.  Visual Studio probably cannot read this .designer file.");
                    }
                    break;

                case ParsingState.AfterNamespace:
                    Error("There should be no more content after the end of the namespace.  Visual Studio probably cannot read this .designer file.");
                    break;
                }
            }

            Verbose("Ended parse of .designer file.");

            return(designerInfo);
        }
Exemple #2
0
        /// <summary>
        /// Compare a parsed markup file against a parsed designer file to determine if they match each other.
        /// </summary>
        /// <param name="compileContext">The context in which errors should be reported.</param>
        /// <param name="filename">The filename to use for reporting errors.</param>
        /// <param name="markupInfo">The markup file to compare.</param>
        /// <param name="designerInfo">The designer file to compare.</param>
        /// <returns>True if they match, false if they do not.</returns>
        private static bool CompareMarkupInfoToDesignerInfo(ICompileContext compileContext, string filename, MarkupInfo markupInfo, DesignerInfo designerInfo)
        {
            compileContext.Verbose("Comparing markup controls to .designer file properties...");

            compileContext.Verbose("Comparing classnames.");

            // First, make sure the type names match; we *should* be talking about the same classes here.
            if (markupInfo.ClassType == null)
            {
                compileContext.Error("{0}: Designer file exists, but markup file has no Inherits=\"...\" attribute.", filename);
                return(false);
            }
            if (markupInfo.ClassType.FullName != designerInfo.FullTypeName)
            {
                compileContext.Error("{0}: Designer file and markup file specify different type names (\"{1}\" in the markup, and \"{2}\" in the designer file.",
                                     filename, markupInfo.ClassType.FullName, designerInfo.FullTypeName);
                return(false);
            }

            // Build lookup tables for the property declarations in the designer file and in the markup file.
            // We'll use these to make searching for property matches that much faster, and to detect duplicates,
            // and to ensure that we're talking about the same set of properties in both files.

            compileContext.Verbose("Checking for duplicate control declarations.");

            Dictionary <string, OutputControl> markupPropertiesByName = new Dictionary <string, OutputControl>();
            Dictionary <string, DesignerPropertyDeclaration> designerProperiesByName = new Dictionary <string, DesignerPropertyDeclaration>();

            List <string> duplicateMarkupProperties = new List <string>();

            foreach (OutputControl outputControl in markupInfo.OutputControls)
            {
                if (string.IsNullOrEmpty(outputControl.Name))
                {
                    continue;
                }

                if (markupPropertiesByName.ContainsKey(outputControl.Name))
                {
                    duplicateMarkupProperties.Add(outputControl.Name);
                }
                else
                {
                    markupPropertiesByName.Add(outputControl.Name, outputControl);
                }
            }

            List <string> duplicateDesignerProperties = new List <string>();

            foreach (DesignerPropertyDeclaration propertyDeclaration in designerInfo.PropertyDeclarations)
            {
                if (designerProperiesByName.ContainsKey(propertyDeclaration.Name))
                {
                    duplicateDesignerProperties.Add(propertyDeclaration.Name);
                }
                else
                {
                    designerProperiesByName.Add(propertyDeclaration.Name, propertyDeclaration);
                }
            }

            // Check the lookup tables for duplicates.  There shouldn't be any.

            if (duplicateMarkupProperties.Count > 0)
            {
                compileContext.Error("{0}: Malformed markup error: Found multiple controls in the markup that have the same ID.  Stopping verification now due to invalid markup file.  Duplicate IDs: {1}",
                                     filename, Join(duplicateMarkupProperties, ", "));
            }
            if (duplicateDesignerProperties.Count > 0)
            {
                compileContext.Error("{0}: Malformed designer error: Found multiple property declarations in the .designer file that have the same name.  Stopping verification now due to invalid designer file.  Duplicate names: {1}",
                                     filename, Join(duplicateDesignerProperties, ", "));
            }
            if (duplicateMarkupProperties.Count > 0 || duplicateDesignerProperties.Count > 0)
            {
                return(false);
            }

            // Okay, now check to see if the markup or designer declare property names that the other doesn't have.

            compileContext.Verbose("Checking for missing control declarations.");

            Type          contentControl            = typeof(System.Web.UI.WebControls.Content);
            List <string> missingDesignerProperties = markupInfo.OutputControls
                                                      .Where(p => !string.IsNullOrEmpty(p.Name) && p.ReflectedControl.ControlType != contentControl && !designerProperiesByName.ContainsKey(p.Name))
                                                      .Select(p => p.Name)
                                                      .ToList();
            List <string> missingMarkupProperties = designerInfo.PropertyDeclarations
                                                    .Where(p => !string.IsNullOrEmpty(p.Name) && !markupPropertiesByName.ContainsKey(p.Name))
                                                    .Select(p => p.Name)
                                                    .ToList();

            if (missingDesignerProperties.Count > 0)
            {
                compileContext.Error("{0}: Missing property error: Found controls declared in the markup that do not exist in the .designer file.  Missing IDs: {1}",
                                     filename, Join(missingDesignerProperties, ", "));
            }
            if (missingMarkupProperties.Count > 0)
            {
                compileContext.Error("{0}: Missing control error: Found property declarations in the .designer file that have no control declaration in the markup.  Missing controls: {1}",
                                     filename, Join(missingMarkupProperties, ", "));
            }

            // We've now established that both files refer to the same set of names.  We now need to check
            // to make sure they all refer to the same control types.

            int numTypeMismatches = 0;

            compileContext.Verbose("Checking for type mismatches.");

            foreach (OutputControl outputControl in markupInfo.OutputControls)
            {
                if (string.IsNullOrEmpty(outputControl.Name) ||
                    outputControl.ReflectedControl.ControlType == contentControl ||
                    !designerProperiesByName.ContainsKey(outputControl.Name))
                {
                    continue;
                }

                DesignerPropertyDeclaration designerPropertyDeclaration = designerProperiesByName[outputControl.Name];
                if (designerPropertyDeclaration.PropertyTypeName != outputControl.ReflectedControl.ControlType.FullName)
                {
                    compileContext.Error("{0}: Type mismatch: Control \"{1}\" has type {2} in the markup but type {3} in the .designer file.",
                                         filename, outputControl.Name, outputControl.ReflectedControl.ControlType.FullName, designerPropertyDeclaration.PropertyTypeName);
                    numTypeMismatches++;
                }
            }

            if (missingDesignerProperties.Count > 0 || missingMarkupProperties.Count > 0 || numTypeMismatches > 0)
            {
                return(false);
            }

            // One last very touchy check:  All the properties exist in both files, and they have the same names and
            // same types --- but are they in the right order?  Visual Studio is very picky about the order, and if
            // they don't match, the Visual Studio designer will break.

            compileContext.Verbose("Checking for mis-ordered declarations.");

            for (int m = 0, d = 0; m < markupInfo.OutputControls.Count;)
            {
                OutputControl outputControl = markupInfo.OutputControls[m++];
                if (string.IsNullOrEmpty(outputControl.Name) ||
                    outputControl.ReflectedControl.ControlType == contentControl)
                {
                    continue;
                }

                DesignerPropertyDeclaration designerPropertyDeclaration = designerInfo.PropertyDeclarations[d++];

                if (designerPropertyDeclaration.Name != outputControl.Name ||
                    designerPropertyDeclaration.PropertyTypeName != outputControl.ReflectedControl.ControlType.FullName)
                {
                    compileContext.Error("{0}: Ordering error: All of the same controls exist in both the markup and the .designer file, but they do not appear in the same order.", filename);
                    return(false);
                }
            }

            compileContext.Verbose("{0}: Success!", filename);
            return(true);
        }