public virtual void MergeFormChanges(CodeCompileUnit unit) { Reparse(); // find InitializeComponent method and the class it is declared in CodeTypeDeclaration formClass = null; CodeMemberMethod initializeComponent = null; foreach (CodeNamespace n in unit.Namespaces) { foreach (CodeTypeDeclaration typeDecl in n.Types) { foreach (CodeTypeMember m in typeDecl.Members) { if (m is CodeMemberMethod && m.Name == "InitializeComponent") { formClass = typeDecl; initializeComponent = (CodeMemberMethod)m; break; } } } } if (formClass == null || initializeComponent == null) { throw new InvalidOperationException("InitializeComponent method not found in framework-generated CodeDom."); } if (this.formClass == null) { MessageService.ShowMessage("Cannot save form: InitializeComponent method does not exist anymore. You should not modify the Designer.cs file while editing a form."); return; } FixGeneratedCode(this.formClass, initializeComponent); // generate file and get initialize components string StringWriter writer = new StringWriter(); CodeDOMGenerator domGenerator = new CodeDOMGenerator(this.CodeDomProvider, tabs + '\t'); domGenerator.ConvertContentDefinition(initializeComponent, writer); string statements = writer.ToString(); // initializeComponents.BodyRegion.BeginLine + 1 DomRegion bodyRegion = GetReplaceRegion(this.ViewContent.DesignerCodeFileDocument, initializeComponents); if (bodyRegion.BeginColumn <= 0 || bodyRegion.EndColumn <= 0) { throw new InvalidOperationException("Column must be > 0"); } int startOffset = this.ViewContent.DesignerCodeFileDocument.PositionToOffset(new TextLocation(bodyRegion.BeginColumn - 1, bodyRegion.BeginLine - 1)); int endOffset = this.ViewContent.DesignerCodeFileDocument.PositionToOffset(new TextLocation(bodyRegion.EndColumn - 1, bodyRegion.EndLine - 1)); this.ViewContent.DesignerCodeFileDocument.Replace(startOffset, endOffset - startOffset, statements); // apply changes the designer made to field declarations // first loop looks for added and changed fields foreach (CodeTypeMember m in formClass.Members) { if (m is CodeMemberField) { CodeMemberField newField = (CodeMemberField)m; IField oldField = GetField(completeClass, newField.Name); if (oldField == null || FieldChanged(oldField, newField)) { AddOrReplaceField(domGenerator, newField); } } } // second loop looks for removed fields List <string> removedFields = new List <string>(); foreach (IField field in completeClass.Fields) { bool found = false; foreach (CodeTypeMember m in formClass.Members) { if (m is CodeMemberField && m.Name == field.Name) { found = true; break; } } if (!found) { removedFields.Add(field.Name); } } // removing fields is done in two steps because // we must not modify the c.Fields collection while it is enumerated removedFields.ForEach(RemoveField); ParserService.EnqueueForParsing(this.ViewContent.DesignerCodeFile.FileName, this.ViewContent.DesignerCodeFileDocument.TextContent); }