The C# Formatter generates a set of text replace actions to format a region in a C# document.
Exemplo n.º 1
1
		public string FormatText (CSharpFormattingPolicy policy, TextStylePolicy textPolicy, string mimeType, string input, int startOffset, int endOffset)
		{
			var data = new TextEditorData ();
			data.Document.SuppressHighlightUpdate = true;
			data.Document.MimeType = mimeType;
			data.Document.FileName = "toformat.cs";
			if (textPolicy != null) {
				data.Options.TabsToSpaces = textPolicy.TabsToSpaces;
				data.Options.TabSize = textPolicy.TabWidth;
				data.Options.IndentationSize = textPolicy.IndentWidth;
				data.Options.IndentStyle = textPolicy.RemoveTrailingWhitespace ? IndentStyle.Virtual : IndentStyle.Smart;
			}
			data.Text = input;

			// System.Console.WriteLine ("-----");
			// System.Console.WriteLine (data.Text.Replace (" ", ".").Replace ("\t", "->"));
			// System.Console.WriteLine ("-----");

			var parser = new CSharpParser ();
			var compilationUnit = parser.Parse (data);
			bool hadErrors = parser.HasErrors;
			
			if (hadErrors) {
				//				foreach (var e in parser.ErrorReportPrinter.Errors)
				//					Console.WriteLine (e.Message);
				return input.Substring (startOffset, Math.Max (0, Math.Min (endOffset, input.Length) - startOffset));
			}

			var originalVersion = data.Document.Version;

			var textEditorOptions = data.CreateNRefactoryTextEditorOptions ();
			var formattingVisitor = new ICSharpCode.NRefactory.CSharp.CSharpFormatter (
				policy.CreateOptions (),
				textEditorOptions
			) {
				FormattingMode = FormattingMode.Intrusive
			};

			var changes = formattingVisitor.AnalyzeFormatting (data.Document, compilationUnit);
			try {
				changes.ApplyChanges (startOffset, endOffset - startOffset);
			} catch (Exception e) {
				LoggingService.LogError ("Error in code formatter", e);
				return input.Substring (startOffset, Math.Max (0, Math.Min (endOffset, input.Length) - startOffset));
			}

			// check if the formatter has produced errors
			parser = new CSharpParser ();
			parser.Parse (data);
			if (parser.HasErrors) {
				LoggingService.LogError ("C# formatter produced source code errors. See console for output.");
				return input.Substring (startOffset, Math.Max (0, Math.Min (endOffset, input.Length) - startOffset));
			}

			var currentVersion = data.Document.Version;

			string result = data.GetTextBetween (startOffset, originalVersion.MoveOffsetTo (currentVersion, endOffset, ICSharpCode.NRefactory.Editor.AnchorMovementType.Default));
			data.Dispose ();
			return result;
		}
Exemplo n.º 2
0
		/// <summary>
		/// Formats the specified part of the document.
		/// </summary>
		public static void Format(ITextEditor editor, int offset, int length, CSharpFormattingOptions options)
		{
			var formatter = new CSharpFormatter(options, editor.ToEditorOptions());
			formatter.AddFormattingRegion(new DomRegion(editor.Document.GetLocation(offset), editor.Document.GetLocation(offset + length)));
			var changes = formatter.AnalyzeFormatting(editor.Document, SyntaxTree.Parse(editor.Document));
			changes.ApplyChanges(offset, length);
		}
Exemplo n.º 3
0
		/// <summary>
		/// Formats the specified part of the document.
		/// </summary>
		public static void Format(ITextEditor editor, int offset, int length, CSharpFormattingOptionsContainer optionsContainer)
		{
			TextEditorOptions editorOptions = editor.ToEditorOptions();
			optionsContainer.CustomizeEditorOptions(editorOptions);
			var formatter = new CSharpFormatter(optionsContainer.GetEffectiveOptions(), editorOptions);
			formatter.AddFormattingRegion(new DomRegion(editor.Document.GetLocation(offset), editor.Document.GetLocation(offset + length)));
			var changes = formatter.AnalyzeFormatting(editor.Document, SyntaxTree.Parse(editor.Document));
			changes.ApplyChanges(offset, length);
		}
Exemplo n.º 4
0
 public CodeFormatResponse Format(CodeFormatRequest request)
 {
     var options = _config.TextEditorOptions;
     var policy = _config.CSharpFormattingOptions;
     var formatter = new CSharpFormatter(policy, options);
     formatter.FormattingMode = FormattingMode.Intrusive;
     var output = formatter.Format(request.Buffer);
     return new CodeFormatResponse(output);
 }
        static FormattingChanges GetFormattingChanges(PolicyContainer policyParent, IEnumerable <string> mimeTypeChain, MonoDevelop.Ide.Gui.Document document, string input, DomRegion formattingRegion, ref int formatStartOffset, ref int formatLength, bool formatLastStatementOnly)
        {
            using (var stubData = TextEditorData.CreateImmutable(input)) {
                stubData.Document.FileName = document.FileName;
                var  parser          = document.HasProject ? new CSharpParser(TypeSystemParser.GetCompilerArguments(document.Project)) : new CSharpParser();
                var  compilationUnit = parser.Parse(stubData);
                bool hadErrors       = parser.HasErrors;
                if (hadErrors)
                {
                    using (var stubData2 = TextEditorData.CreateImmutable(input + "}")) {
                        compilationUnit = parser.Parse(stubData2);
                        hadErrors       = parser.HasErrors;
                    }
                }
                // try it out, if the behavior is better when working only with correct code.
                if (hadErrors)
                {
                    return(null);
                }

                var policy = policyParent.Get <CSharpFormattingPolicy> (mimeTypeChain);

                var formattingVisitor = new ICSharpCode.NRefactory.CSharp.CSharpFormatter(policy.CreateOptions(), document.Editor.CreateNRefactoryTextEditorOptions());
                formattingVisitor.FormattingMode = FormattingMode.Intrusive;
                formattingVisitor.AddFormattingRegion(formattingRegion);


                var changes = formattingVisitor.AnalyzeFormatting(stubData.Document, compilationUnit);

                if (formatLastStatementOnly)
                {
                    AstNode node = compilationUnit.GetAdjacentNodeAt <Statement> (stubData.OffsetToLocation(formatStartOffset + formatLength - 1));
                    if (node != null)
                    {
                        while (node.Role == Roles.EmbeddedStatement || node.Role == IfElseStatement.TrueRole || node.Role == IfElseStatement.FalseRole)
                        {
                            node = node.Parent;
                        }
                        // include indentation if node starts in new line
                        var formatNode = node.GetPrevNode();
                        if (formatNode.Role != Roles.NewLine)
                        {
                            formatNode = node;
                        }
                        var start = stubData.LocationToOffset(formatNode.StartLocation);
                        if (start > formatStartOffset)
                        {
                            var end = stubData.LocationToOffset(node.EndLocation);
                            formatStartOffset = start;
                            formatLength      = end - start;
                        }
                    }
                }
                return(changes);
            }
        }
Exemplo n.º 6
0
        //public static CSharpFormattingOptions tModLoaderFormat = FormattingOptionsFactory.CreateAllman();

        public static string FormatCode(string text, CSharpFormattingOptions options, CancellationToken ct) {
            var formatter = new CSharpFormatter(options) { FormattingMode = FormattingMode.Intrusive };
            text = text.Replace("\r\n\r\n", "\r\n");

            var doc = new StringBuilderDocument(text);
            var syntaxTree = SyntaxTree.Parse(doc, doc.FileName, null, ct);
            formatter.AnalyzeFormatting(doc, syntaxTree, ct).ApplyChanges();

            return doc.Text;
        }
Exemplo n.º 7
0
		protected static FormattingChanges GetChanges(CSharpFormattingOptions policy, string input, out StringBuilderDocument document, FormattingMode mode = FormattingMode.Intrusive, TextEditorOptions options = null)
		{
			options = GetActualOptions(options);
			input = NormalizeNewlines(input);

			document = new StringBuilderDocument(input);
			var visitor = new CSharpFormatter(policy, options);
			visitor.FormattingMode = mode;
			var syntaxTree = new CSharpParser().Parse(document, "test.cs");

			return visitor.AnalyzeFormatting(document, syntaxTree);
		}
Exemplo n.º 8
0
 protected static void Continue(CSharpFormattingOptions policy, IDocument document, string expectedOutput, FormattingMode formattingMode = FormattingMode.OnTheFly)
 {
     expectedOutput = NormalizeNewlines (expectedOutput);
     var options = new TextEditorOptions ();
     options.EolMarker = "\n";
     var formatter = new CSharpFormatter (policy, options);
     formatter.FormattingMode = formattingMode;
     string newText = formatter.Format (document);
     if (expectedOutput != newText) {
         Console.WriteLine (newText);
     }
     Assert.AreEqual (expectedOutput, newText);
 }
Exemplo n.º 9
0
 /*public static string ApplyChanges (string text, List<TextReplaceAction> changes)
 {
     changes.Sort ((x, y) => y.Offset.CompareTo (x.Offset));
     StringBuilder b = new StringBuilder(text);
     foreach (var change in changes) {
         //Console.WriteLine ("---- apply:" + change);
 //				Console.WriteLine (adapter.Text);
         if (change.Offset > b.Length)
             continue;
         b.Remove(change.Offset, change.RemovedChars);
         b.Insert(change.Offset, change.InsertedText);
     }
 //			Console.WriteLine ("---result:");
 //			Console.WriteLine (adapter.Text);
     return b.ToString();
 }*/
 protected static IDocument GetResult(CSharpFormattingOptions policy, string input, FormattingMode mode = FormattingMode.Intrusive)
 {
     input = NormalizeNewlines(input);
     var document = new StringBuilderDocument(input);
     var options = new TextEditorOptions();
     options.EolMarker = "\n";
     options.WrapLineLength = 80;
     var visitor = new CSharpFormatter (policy, options);
     visitor.FormattingMode = mode;
     var syntaxTree = new CSharpParser ().Parse (document, "test.cs");
     var changes = visitor.AnalyzeFormatting(document, syntaxTree);
     changes.ApplyChanges();
     return document;
 }
Exemplo n.º 10
0
		/// <summary>
		/// Formats the specified part of the document.
		/// </summary>
		public static void Format(ITextEditor editor, int offset, int length, CSharpFormattingOptionsContainer optionsContainer)
		{
			SyntaxTree syntaxTree = SyntaxTree.Parse(editor.Document);
			if (syntaxTree.Errors.Count > 0) {
				// Don't format files containing syntax errors!
				return;
			}
			
			TextEditorOptions editorOptions = editor.ToEditorOptions();
			optionsContainer.CustomizeEditorOptions(editorOptions);
			var formatter = new CSharpFormatter(optionsContainer.GetEffectiveOptions(), editorOptions);
			formatter.AddFormattingRegion(new DomRegion(editor.Document.GetLocation(offset), editor.Document.GetLocation(offset + length)));
			var changes = formatter.AnalyzeFormatting(editor.Document, syntaxTree);
			changes.ApplyChanges(offset, length);
		}
Exemplo n.º 11
0
        public FormattingVisitor(CSharpFormatter formatter, IDocument document, FormattingChanges changes, CancellationToken token)
        {
            if (formatter == null)
                throw new ArgumentNullException("formatter");
            if (document == null)
                throw new ArgumentNullException("document");
            if (changes == null)
                throw new ArgumentNullException("changes");

            this.formatter = formatter;
            this.changes = changes;
            this.document = document;
            this.token = token;

            curIndent = new Indent(formatter.TextEditorOptions);
        }
Exemplo n.º 12
0
        public FormattingVisitor(CSharpFormatter formatter, IDocument document, FormattingChanges changes, CancellationToken token)
        {
            if (formatter == null)
            {
                throw new ArgumentNullException("formatter");
            }
            if (document == null)
            {
                throw new ArgumentNullException("document");
            }
            if (changes == null)
            {
                throw new ArgumentNullException("changes");
            }

            this.formatter = formatter;
            this.changes   = changes;
            this.document  = document;
            this.token     = token;

            curIndent = new Indent(formatter.TextEditorOptions);
        }
Exemplo n.º 13
0
		static FormattingChanges GetFormattingChanges (PolicyContainer policyParent, IEnumerable<string> mimeTypeChain, MonoDevelop.Ide.Gui.Document document, string input, DomRegion formattingRegion, ref int formatStartOffset, ref int formatLength, bool formatLastStatementOnly)
		{
			using (var stubData = TextEditorData.CreateImmutable (input)) {
				stubData.Document.FileName = document.FileName;
				var parser = document.HasProject ? new CSharpParser (TypeSystemParser.GetCompilerArguments (document.Project)) : new CSharpParser ();
				var compilationUnit = parser.Parse (stubData);
				bool hadErrors = parser.HasErrors;
				if (hadErrors) {
					using (var stubData2 = TextEditorData.CreateImmutable (input + "}")) {
						compilationUnit = parser.Parse (stubData2);
						hadErrors = parser.HasErrors;
					}
				}
				// try it out, if the behavior is better when working only with correct code.
				if (hadErrors) {
					return null;
				}
				
				var policy = policyParent.Get<CSharpFormattingPolicy> (mimeTypeChain);
				
				var formattingVisitor = new ICSharpCode.NRefactory.CSharp.CSharpFormatter (policy.CreateOptions (), document.Editor.CreateNRefactoryTextEditorOptions ());
				formattingVisitor.FormattingMode = FormattingMode.Intrusive;
				formattingVisitor.AddFormattingRegion (formattingRegion);


				var changes = formattingVisitor.AnalyzeFormatting (stubData.Document, compilationUnit);

				if (formatLastStatementOnly) {
					AstNode node = compilationUnit.GetAdjacentNodeAt<Statement> (stubData.OffsetToLocation (formatStartOffset + formatLength - 1));
					if (node != null) {
						while (node.Role == Roles.EmbeddedStatement || node.Role == IfElseStatement.TrueRole || node.Role == IfElseStatement.FalseRole)
							node = node.Parent;
						// include indentation if node starts in new line
						var formatNode = node.GetPrevNode ();
						if (formatNode.Role != Roles.NewLine)
							formatNode = node;
						var start = stubData.LocationToOffset (formatNode.StartLocation);
						if (start > formatStartOffset) {
							var end = stubData.LocationToOffset (node.EndLocation);
							formatStartOffset = start;
							formatLength = end - start;
						}
					}
				}
				return changes;
			}
		}
        public override void Complete(ICSharpCode.AvalonEdit.Editing.TextArea textArea, ISegment completionSegment, EventArgs insertionRequestEventArgs)
        {
            if (declarationBegin > completionSegment.Offset)
            {
                base.Complete(textArea, completionSegment, insertionRequestEventArgs);
                return;
            }
            TypeSystemAstBuilder b = new TypeSystemAstBuilder(new CSharpResolver(contextAtCaret));
            b.ShowTypeParameterConstraints = false;
            b.GenerateBody = true;

            var entityDeclaration = b.ConvertEntity(this.Entity);
            entityDeclaration.Modifiers &= ~(Modifiers.Virtual | Modifiers.Abstract);
            entityDeclaration.Modifiers |= Modifiers.Override;

            if (!this.Entity.IsAbstract)
            {
                // modify body to call the base method
                if (this.Entity.EntityType == EntityType.Method)
                {
                    var baseCall = new BaseReferenceExpression().Invoke(this.Entity.Name, ParametersToExpressions(this.Entity));
                    var body = entityDeclaration.GetChildByRole(Roles.Body);
                    body.Statements.Clear();
                    if (((IMethod)this.Entity).ReturnType.IsKnownType(KnownTypeCode.Void))
                        body.Statements.Add(new ExpressionStatement(baseCall));
                    else
                        body.Statements.Add(new ReturnStatement(baseCall));
                }
                else if (this.Entity.EntityType == EntityType.Indexer || this.Entity.EntityType == EntityType.Property)
                {
                    Expression baseCall;
                    if (this.Entity.EntityType == EntityType.Indexer)
                        baseCall = new BaseReferenceExpression().Indexer(ParametersToExpressions(this.Entity));
                    else
                        baseCall = new BaseReferenceExpression().Member(this.Entity.Name);
                    var getterBody = entityDeclaration.GetChildByRole(PropertyDeclaration.GetterRole).Body;
                    if (!getterBody.IsNull)
                    {
                        getterBody.Statements.Clear();
                        getterBody.Add(new ReturnStatement(baseCall.Clone()));
                    }
                    var setterBody = entityDeclaration.GetChildByRole(PropertyDeclaration.SetterRole).Body;
                    if (!setterBody.IsNull)
                    {
                        setterBody.Statements.Clear();
                        setterBody.Add(new AssignmentExpression(baseCall.Clone(), new IdentifierExpression("value")));
                    }
                }
            }

            var document = textArea.Document;
            StringWriter w = new StringWriter();
            var formattingOptions = FormattingOptionsFactory.CreateSharpDevelop();
            var segmentDict = SegmentTrackingOutputFormatter.WriteNode(w, entityDeclaration, formattingOptions, textArea.Options);

            string newText = w.ToString().TrimEnd();
            document.Replace(declarationBegin, completionSegment.EndOffset - declarationBegin, newText);
            var throwStatement = entityDeclaration.Descendants.FirstOrDefault(n => n is ThrowStatement);
            if (throwStatement != null)
            {
                var segment = segmentDict[throwStatement];
                textArea.Selection = new RectangleSelection(textArea, new TextViewPosition(textArea.Document.GetLocation(declarationBegin + segment.Offset)), new TextViewPosition(textArea.Document.GetLocation(declarationBegin + segment.Offset + segment.Length)));
            }

            //format the inserted code nicely
            var formatter = new CSharpFormatter(formattingOptions);
            formatter.AddFormattingRegion(new DomRegion(document.GetLocation(declarationBegin), document.GetLocation(declarationBegin + newText.Length)));
            var syntaxTree = new CSharpParser().Parse(document);
            formatter.AnalyzeFormatting(document, syntaxTree).ApplyChanges();
        }
Exemplo n.º 15
0
		/// <summary>
		/// Formats the file
		/// </summary>
		static string FormatFile (ICSharpCode.NRefactory.CSharp.SyntaxTree file)
		{
			var formatting = FormattingOptionsFactory.CreateMono ();
			formatting.AutoPropertyFormatting = PropertyFormatting.ForceOneLine;
			formatting.SimplePropertyFormatting = PropertyFormatting.ForceOneLine;

			var formatter = new CSharpFormatter (formatting) {
				FormattingMode = FormattingMode.Intrusive
			};

			return formatter.Format (file.ToString ());
		}
Exemplo n.º 16
0
        /// <summary>
        /// Build the script
        /// </summary>
        private void BuildScript()
        {
            this.explorerPresenter.CommandHistory.ModelChanged -= new CommandHistory.ModelChangedDelegate(this.CommandHistory_ModelChanged);

            try
            {
                // format the code first.
                string code = this.managerView.Editor.Text;
                code = new CSharpFormatter(FormattingOptionsFactory.CreateAllman()).Format(code);

                // set the code property manually first so that compile error can be trapped via
                // an exception.
                this.manager.Code = code;

                // If it gets this far then compiles ok.
                this.explorerPresenter.CommandHistory.Add(new Commands.ChangeProperty(this.manager, "Code", code));

                this.explorerPresenter.MainPresenter.ShowMessage("Manager script compiled successfully", DataStore.ErrorLevel.Information);
            }
            catch (Models.Core.ApsimXException err)
            {
                string msg = err.Message;
                if (err.InnerException != null)
                    this.explorerPresenter.MainPresenter.ShowMessage(string.Format("[{0}]: {1}", err.model.Name, err.InnerException.Message), DataStore.ErrorLevel.Error);
                else
                    this.explorerPresenter.MainPresenter.ShowMessage(string.Format("[{0}]: {1}", err.model.Name, err.Message), DataStore.ErrorLevel.Error);
            }
            this.explorerPresenter.CommandHistory.ModelChanged += new CommandHistory.ModelChangedDelegate(this.CommandHistory_ModelChanged);
        }
Exemplo n.º 17
0
        public static string FormatText(CSharpFormattingPolicy policy, TextStylePolicy textPolicy, string mimeType, string input, int startOffset, int endOffset)
        {
            var data = new TextEditorData();

            data.Document.SuppressHighlightUpdate = true;
            data.Document.MimeType = mimeType;
            data.Document.FileName = "toformat.cs";
            if (textPolicy != null)
            {
                data.Options.TabsToSpaces    = textPolicy.TabsToSpaces;
                data.Options.TabSize         = textPolicy.TabWidth;
                data.Options.IndentationSize = textPolicy.IndentWidth;
                data.Options.IndentStyle     = textPolicy.RemoveTrailingWhitespace ? IndentStyle.Virtual : IndentStyle.Smart;
            }
            data.Text = input;

            // System.Console.WriteLine ("-----");
            // System.Console.WriteLine (data.Text.Replace (" ", ".").Replace ("\t", "->"));
            // System.Console.WriteLine ("-----");

            var  parser          = new CSharpParser();
            var  compilationUnit = parser.Parse(data);
            bool hadErrors       = parser.HasErrors;

            if (hadErrors)
            {
                //				foreach (var e in parser.ErrorReportPrinter.Errors)
                //					Console.WriteLine (e.Message);
                return(input.Substring(startOffset, Math.Max(0, Math.Min(endOffset, input.Length) - startOffset)));
            }

            var originalVersion = data.Document.Version;

            var textEditorOptions = data.CreateNRefactoryTextEditorOptions();
            var formattingVisitor = new ICSharpCode.NRefactory.CSharp.CSharpFormatter(
                policy.CreateOptions(),
                textEditorOptions
                )
            {
                FormattingMode = FormattingMode.Intrusive
            };

            var changes = formattingVisitor.AnalyzeFormatting(data.Document, compilationUnit);

            try {
                changes.ApplyChanges(startOffset, endOffset - startOffset);
            } catch (Exception e) {
                LoggingService.LogError("Error in code formatter", e);
                return(input.Substring(startOffset, Math.Max(0, Math.Min(endOffset, input.Length) - startOffset)));
            }

            // check if the formatter has produced errors
            parser = new CSharpParser();
            parser.Parse(data);
            if (parser.HasErrors)
            {
                LoggingService.LogError("C# formatter produced source code errors. See console for output.");
                return(input.Substring(startOffset, Math.Max(0, Math.Min(endOffset, input.Length) - startOffset)));
            }

            var currentVersion = data.Document.Version;

            string result = data.GetTextBetween(startOffset, originalVersion.MoveOffsetTo(currentVersion, endOffset));

            data.Dispose();
            return(result);
        }
Exemplo n.º 18
0
        /// <summary>
        /// Save the contents of the textbox into the specified file. If doing the save on the same file, we need to
        /// suspend notifications for file changes during the save operation.
        /// </summary>
        /// <param name="pszFilename">Pointer to the file name. If the pszFilename parameter is a null reference 
        /// we need to save using the current file
        /// </param>
        /// <param name="fRemember">Boolean value that indicates whether the pszFileName parameter is to be used 
        /// as the current working file.
        /// If remember != 0, pszFileName needs to be made the current file and the dirty flag needs to be cleared after the save.
        ///                   Also, file notifications need to be enabled for the new file and disabled for the old file 
        /// If remember == 0, this save operation is a Save a Copy As operation. In this case, 
        ///                   the current file is unchanged and dirty flag is not cleared
        /// </param>
        /// <param name="nFormatIndex">Zero based index into the list of formats that indicates the format in which 
        /// the file will be saved</param>
        /// <returns>S_OK if the method succeeds</returns>
        int IPersistFileFormat.Save(string pszFilename, int fRemember, uint nFormatIndex)
        {
            var hr = VSConstants.S_OK;
            var doingSaveOnSameFile = false;
            // If file is null or same --> SAVE
            if (pszFilename == null || pszFilename == _fileName)
            {
                fRemember = 1;
                doingSaveOnSameFile = true;
            }

            //Suspend file change notifications for only Save since we don't have notifications setup
            //for SaveAs and SaveCopyAs (as they are different files)
            if (doingSaveOnSameFile)
                SuspendFileChangeNotification(pszFilename, 1);

            try
            {
                var configForSaving = _editorControl.Config.Clone();
                var configProjectItem = _myPackage.GetEnvDTE().Solution.FindProjectItem(pszFilename);

                if (configForSaving.DesignerConnection.Authentication.AuthenticationType == AuthenticationType.SqlAuthentication)
                {
                    var sqlAuth = configForSaving.DesignerConnection.Authentication;
                    if (sqlAuth.SavePassword)
                    {
                        var uniqueId = GetUniqueId(pszFilename);
                        if (_myPackage.Passwords.ContainsKey(uniqueId))
                        {
                            _myPackage.Passwords[uniqueId] = sqlAuth.Password;
                        }
                        else
                        {
                            _myPackage.Passwords.Add(uniqueId, sqlAuth.Password);
                        }
                    }

                    sqlAuth.Password = "******";
                }


                var configSerialized = JsonConvert.SerializeObject(configForSaving, Formatting.Indented, new StringEnumConverter());
                File.WriteAllText(_fileName, configSerialized);

                var configProjectItemChildren = configProjectItem.ProjectItems;

                var codeProjectItem =
                    configProjectItemChildren
                        .Cast<ProjectItem>()
                        .FirstOrDefault(item => item.Name.ToUpper().EndsWith(".cs".ToUpper()));

                if (codeProjectItem != null)
                {
                    var codeFileName = codeProjectItem.FileNames[0];
                    SuspendFileChangeNotification(codeFileName, 1);
                    try
                    {
                        var formattingOptions = FormattingOptionsFactory.CreateAllman();
                        formattingOptions.AlignElseInIfStatements = true;
                        formattingOptions.ArrayInitializerWrapping = Wrapping.WrapIfTooLong;
                        formattingOptions.ChainedMethodCallWrapping = Wrapping.WrapIfTooLong;
                        formattingOptions.AutoPropertyFormatting = PropertyFormatting.ForceOneLine;
                        formattingOptions.IndexerArgumentWrapping = Wrapping.WrapIfTooLong;
                        formattingOptions.IndexerClosingBracketOnNewLine = NewLinePlacement.SameLine;
                        formattingOptions.IndexerDeclarationClosingBracketOnNewLine = NewLinePlacement.SameLine;
                        formattingOptions.IndexerDeclarationParameterWrapping = Wrapping.WrapIfTooLong;
                        formattingOptions.MethodCallArgumentWrapping = Wrapping.WrapIfTooLong;
                        formattingOptions.MethodCallClosingParenthesesOnNewLine = NewLinePlacement.SameLine;
                        formattingOptions.MethodDeclarationClosingParenthesesOnNewLine = NewLinePlacement.SameLine;
                        formattingOptions.MethodDeclarationParameterWrapping = Wrapping.WrapIfTooLong;

                        formattingOptions.NewLineAferIndexerDeclarationOpenBracket = NewLinePlacement.SameLine;
                        formattingOptions.NewLineAferIndexerOpenBracket = NewLinePlacement.SameLine;
                        formattingOptions.NewLineAferMethodCallOpenParentheses = NewLinePlacement.SameLine;
                        formattingOptions.NewLineAferMethodDeclarationOpenParentheses = NewLinePlacement.SameLine;

                        // determine if the framework supports async
                        var project = (uint) codeProjectItem.ContainingProject.Properties.Item("TargetFramework").Value;
                        var supportsAsync = (project >> 16 > 4) || ((project >> 16 == 4) && (project - ((project >> 16) << 16) >= 5));

                        var formattedCode =
                            new CSharpFormatter(FormattingOptionsFactory.CreateAllman()).Format(
                                new Main(_editorControl.Config, supportsAsync).GetCode());

                        File.WriteAllText(codeFileName, formattedCode);
                    }
                    finally
                    {
                        SuspendFileChangeNotification(codeFileName, 0);
                    }
                }

            }
            catch (ArgumentException)
            {
                hr = VSConstants.E_FAIL;
            }
            catch (IOException)
            {
                hr = VSConstants.E_FAIL;
            }
            finally
            {
                //restore the file change notifications
                if (doingSaveOnSameFile)
                    SuspendFileChangeNotification(pszFilename, 0);
            }

            if (VSConstants.E_FAIL == hr)
                return hr;

            //Save and Save as
            if (fRemember != 0)
            {
                //Save as
                if (null != pszFilename && !_fileName.Equals(pszFilename))
                {
                    SetFileChangeNotification(_fileName, false); //remove notification from old file
                    SetFileChangeNotification(pszFilename, true); //add notification for new file
                    _fileName = pszFilename;     //cache the new file name
                }
                _isDirty = false;
                SetReadOnly(false);             //set read only to false since you were successfully able
                                                //to save to the new file                                                    
            }

            var track = TrackSelection;
            if (null != track)
            {
                hr = track.OnSelectChange(_selContainer);
            }

            // Since all changes are now saved properly to disk, there's no need for a backup.
            _backupObsolete = false;
            return hr;
        }