├── .gitattributes
├── .github
└── FUNDING.yml
├── .gitignore
├── CodeCleanupOnSave.sln
├── LICENSE
├── README.md
├── appveyor.yml
├── art
├── code-cleanup-menu.png
└── options.png
└── src
├── CodeCleanupOnSave.csproj
├── CodeCleanupOnSavePackage.cs
├── Options
├── BaseOptionModel.cs
├── BaseOptionPage.cs
├── DialogPageProvider.cs
└── GeneralOptions.cs
├── Properties
└── AssemblyInfo.cs
├── Resources
└── Icon.png
├── RunOnSave.cs
├── SaveHandler.cs
├── VSCommandTable.cs
├── VSCommandTable.vsct
├── source.extension.cs
└── source.extension.vsixmanifest
/.gitattributes:
--------------------------------------------------------------------------------
1 | ###############################################################################
2 | # Set default behavior to automatically normalize line endings.
3 | ###############################################################################
4 | * text=auto
5 |
6 | ###############################################################################
7 | # Set default behavior for command prompt diff.
8 | #
9 | # This is need for earlier builds of msysgit that does not have it on by
10 | # default for csharp files.
11 | # Note: This is only used by command line
12 | ###############################################################################
13 | #*.cs diff=csharp
14 |
15 | ###############################################################################
16 | # Set the merge driver for project and solution files
17 | #
18 | # Merging from the command prompt will add diff markers to the files if there
19 | # are conflicts (Merging from VS is not affected by the settings below, in VS
20 | # the diff markers are never inserted). Diff markers may cause the following
21 | # file extensions to fail to load in VS. An alternative would be to treat
22 | # these files as binary and thus will always conflict and require user
23 | # intervention with every merge. To do so, just uncomment the entries below
24 | ###############################################################################
25 | #*.sln merge=binary
26 | #*.csproj merge=binary
27 | #*.vbproj merge=binary
28 | #*.vcxproj merge=binary
29 | #*.vcproj merge=binary
30 | #*.dbproj merge=binary
31 | #*.fsproj merge=binary
32 | #*.lsproj merge=binary
33 | #*.wixproj merge=binary
34 | #*.modelproj merge=binary
35 | #*.sqlproj merge=binary
36 | #*.wwaproj merge=binary
37 |
38 | ###############################################################################
39 | # behavior for image files
40 | #
41 | # image files are treated as binary by default.
42 | ###############################################################################
43 | #*.jpg binary
44 | #*.png binary
45 | #*.gif binary
46 |
47 | ###############################################################################
48 | # diff behavior for common document formats
49 | #
50 | # Convert binary document formats to text before diffing them. This feature
51 | # is only available from the command line. Turn it on by uncommenting the
52 | # entries below.
53 | ###############################################################################
54 | #*.doc diff=astextplain
55 | #*.DOC diff=astextplain
56 | #*.docx diff=astextplain
57 | #*.DOCX diff=astextplain
58 | #*.dot diff=astextplain
59 | #*.DOT diff=astextplain
60 | #*.pdf diff=astextplain
61 | #*.PDF diff=astextplain
62 | #*.rtf diff=astextplain
63 | #*.RTF diff=astextplain
64 |
--------------------------------------------------------------------------------
/.github/FUNDING.yml:
--------------------------------------------------------------------------------
1 | # These are supported funding model platforms
2 |
3 | github: madskristensen
4 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | ## Ignore Visual Studio temporary files, build results, and
2 | ## files generated by popular Visual Studio add-ons.
3 |
4 | # User-specific files
5 | *.suo
6 | *.user
7 | *.userosscache
8 | *.sln.docstates
9 |
10 | # User-specific files (MonoDevelop/Xamarin Studio)
11 | *.userprefs
12 |
13 | # Build results
14 | [Dd]ebug/
15 | [Dd]ebugPublic/
16 | [Rr]elease/
17 | [Rr]eleases/
18 | x64/
19 | x86/
20 | bld/
21 | [Bb]in/
22 | [Oo]bj/
23 | [Ll]og/
24 |
25 | # Visual Studio 2015 cache/options directory
26 | .vs/
27 | # Uncomment if you have tasks that create the project's static files in wwwroot
28 | #wwwroot/
29 |
30 | # MSTest test Results
31 | [Tt]est[Rr]esult*/
32 | [Bb]uild[Ll]og.*
33 |
34 | # NUNIT
35 | *.VisualState.xml
36 | TestResult.xml
37 |
38 | # Build Results of an ATL Project
39 | [Dd]ebugPS/
40 | [Rr]eleasePS/
41 | dlldata.c
42 |
43 | # DNX
44 | project.lock.json
45 | project.fragment.lock.json
46 | artifacts/
47 |
48 | *_i.c
49 | *_p.c
50 | *_i.h
51 | *.ilk
52 | *.meta
53 | *.obj
54 | *.pch
55 | *.pdb
56 | *.pgc
57 | *.pgd
58 | *.rsp
59 | *.sbr
60 | *.tlb
61 | *.tli
62 | *.tlh
63 | *.tmp
64 | *.tmp_proj
65 | *.log
66 | *.vspscc
67 | *.vssscc
68 | .builds
69 | *.pidb
70 | *.svclog
71 | *.scc
72 |
73 | # Chutzpah Test files
74 | _Chutzpah*
75 |
76 | # Visual C++ cache files
77 | ipch/
78 | *.aps
79 | *.ncb
80 | *.opendb
81 | *.opensdf
82 | *.sdf
83 | *.cachefile
84 | *.VC.db
85 | *.VC.VC.opendb
86 |
87 | # Visual Studio profiler
88 | *.psess
89 | *.vsp
90 | *.vspx
91 | *.sap
92 |
93 | # TFS 2012 Local Workspace
94 | $tf/
95 |
96 | # Guidance Automation Toolkit
97 | *.gpState
98 |
99 | # ReSharper is a .NET coding add-in
100 | _ReSharper*/
101 | *.[Rr]e[Ss]harper
102 | *.DotSettings.user
103 |
104 | # JustCode is a .NET coding add-in
105 | .JustCode
106 |
107 | # TeamCity is a build add-in
108 | _TeamCity*
109 |
110 | # DotCover is a Code Coverage Tool
111 | *.dotCover
112 |
113 | # NCrunch
114 | _NCrunch_*
115 | .*crunch*.local.xml
116 | nCrunchTemp_*
117 |
118 | # MightyMoose
119 | *.mm.*
120 | AutoTest.Net/
121 |
122 | # Web workbench (sass)
123 | .sass-cache/
124 |
125 | # Installshield output folder
126 | [Ee]xpress/
127 |
128 | # DocProject is a documentation generator add-in
129 | DocProject/buildhelp/
130 | DocProject/Help/*.HxT
131 | DocProject/Help/*.HxC
132 | DocProject/Help/*.hhc
133 | DocProject/Help/*.hhk
134 | DocProject/Help/*.hhp
135 | DocProject/Help/Html2
136 | DocProject/Help/html
137 |
138 | # Click-Once directory
139 | publish/
140 |
141 | # Publish Web Output
142 | *.[Pp]ublish.xml
143 | *.azurePubxml
144 | # TODO: Comment the next line if you want to checkin your web deploy settings
145 | # but database connection strings (with potential passwords) will be unencrypted
146 | #*.pubxml
147 | *.publishproj
148 |
149 | # Microsoft Azure Web App publish settings. Comment the next line if you want to
150 | # checkin your Azure Web App publish settings, but sensitive information contained
151 | # in these scripts will be unencrypted
152 | PublishScripts/
153 |
154 | # NuGet Packages
155 | *.nupkg
156 | # The packages folder can be ignored because of Package Restore
157 | **/packages/*
158 | # except build/, which is used as an MSBuild target.
159 | !**/packages/build/
160 | # Uncomment if necessary however generally it will be regenerated when needed
161 | #!**/packages/repositories.config
162 | # NuGet v3's project.json files produces more ignoreable files
163 | *.nuget.props
164 | *.nuget.targets
165 |
166 | # Microsoft Azure Build Output
167 | csx/
168 | *.build.csdef
169 |
170 | # Microsoft Azure Emulator
171 | ecf/
172 | rcf/
173 |
174 | # Windows Store app package directories and files
175 | AppPackages/
176 | BundleArtifacts/
177 | Package.StoreAssociation.xml
178 | _pkginfo.txt
179 |
180 | # Visual Studio cache files
181 | # files ending in .cache can be ignored
182 | *.[Cc]ache
183 | # but keep track of directories ending in .cache
184 | !*.[Cc]ache/
185 |
186 | # Others
187 | ClientBin/
188 | ~$*
189 | *~
190 | *.dbmdl
191 | *.dbproj.schemaview
192 | *.jfm
193 | *.pfx
194 | *.publishsettings
195 | node_modules/
196 | orleans.codegen.cs
197 |
198 | # Since there are multiple workflows, uncomment next line to ignore bower_components
199 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
200 | #bower_components/
201 |
202 | # RIA/Silverlight projects
203 | Generated_Code/
204 |
205 | # Backup & report files from converting an old project file
206 | # to a newer Visual Studio version. Backup files are not needed,
207 | # because we have git ;-)
208 | _UpgradeReport_Files/
209 | Backup*/
210 | UpgradeLog*.XML
211 | UpgradeLog*.htm
212 |
213 | # SQL Server files
214 | *.mdf
215 | *.ldf
216 |
217 | # Business Intelligence projects
218 | *.rdl.data
219 | *.bim.layout
220 | *.bim_*.settings
221 |
222 | # Microsoft Fakes
223 | FakesAssemblies/
224 |
225 | # GhostDoc plugin setting file
226 | *.GhostDoc.xml
227 |
228 | # Node.js Tools for Visual Studio
229 | .ntvs_analysis.dat
230 |
231 | # Visual Studio 6 build log
232 | *.plg
233 |
234 | # Visual Studio 6 workspace options file
235 | *.opt
236 |
237 | # Visual Studio LightSwitch build output
238 | **/*.HTMLClient/GeneratedArtifacts
239 | **/*.DesktopClient/GeneratedArtifacts
240 | **/*.DesktopClient/ModelManifest.xml
241 | **/*.Server/GeneratedArtifacts
242 | **/*.Server/ModelManifest.xml
243 | _Pvt_Extensions
244 |
245 | # Paket dependency manager
246 | .paket/paket.exe
247 | paket-files/
248 |
249 | # FAKE - F# Make
250 | .fake/
251 |
252 | # JetBrains Rider
253 | .idea/
254 | *.sln.iml
255 |
256 | # CodeRush
257 | .cr/
258 |
259 | # Python Tools for Visual Studio (PTVS)
260 | __pycache__/
261 | *.pyc
--------------------------------------------------------------------------------
/CodeCleanupOnSave.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | # Visual Studio Version 16
4 | VisualStudioVersion = 16.0.28802.11
5 | MinimumVisualStudioVersion = 10.0.40219.1
6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CodeCleanupOnSave", "src\CodeCleanupOnSave.csproj", "{CBFA76B5-F552-451C-9F07-3FA6B248E0F4}"
7 | EndProject
8 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{D4516910-A9EF-4965-A3E7-CC9AF1A7490B}"
9 | ProjectSection(SolutionItems) = preProject
10 | appveyor.yml = appveyor.yml
11 | README.md = README.md
12 | EndProjectSection
13 | EndProject
14 | Global
15 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
16 | Debug|Any CPU = Debug|Any CPU
17 | Release|Any CPU = Release|Any CPU
18 | EndGlobalSection
19 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
20 | {CBFA76B5-F552-451C-9F07-3FA6B248E0F4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
21 | {CBFA76B5-F552-451C-9F07-3FA6B248E0F4}.Debug|Any CPU.Build.0 = Debug|Any CPU
22 | {CBFA76B5-F552-451C-9F07-3FA6B248E0F4}.Release|Any CPU.ActiveCfg = Release|Any CPU
23 | {CBFA76B5-F552-451C-9F07-3FA6B248E0F4}.Release|Any CPU.Build.0 = Release|Any CPU
24 | EndGlobalSection
25 | GlobalSection(SolutionProperties) = preSolution
26 | HideSolutionNode = FALSE
27 | EndGlobalSection
28 | GlobalSection(ExtensibilityGlobals) = postSolution
29 | SolutionGuid = {D73D5AB2-E858-46AA-AED0-AA631A44DBA8}
30 | EndGlobalSection
31 | EndGlobal
32 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Copyright 2019 Mads Kristensen
2 |
3 | Licensed under the Apache License, Version 2.0 (the "License");
4 | you may not use this file except in compliance with the License.
5 | You may obtain a copy of the License at
6 |
7 | http://www.apache.org/licenses/LICENSE-2.0
8 |
9 | Unless required by applicable law or agreed to in writing, software
10 | distributed under the License is distributed on an "AS IS" BASIS,
11 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | See the License for the specific language governing permissions and
13 | limitations under the License.
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Code Cleanup On Save
2 |
3 | [](https://ci.appveyor.com/project/madskristensen/codecleanuponsave)
4 |
5 | Automatically run one of the Code Clean profiles when saving the document. This ensures your code is always formatted correctly and follows your coding style conventions.
6 |
7 | Download the extension at the
8 | [Visual Studio Marketplace](https://marketplace.visualstudio.com/items?itemName=MadsKristensen.CodeCleanupOnSave)
9 | or try the
10 | [CI build](http://vsixgallery.com/extension/66985471-b701-4851-a2d7-5a8bdce1e694/).
11 |
12 | ---------------------------------------
13 |
14 | Code Cleanup is a new feature of Visual Studio 2019 that will automatically clean up your code file to make sure it is formatted correctly and that your coding style preferences are applied.
15 |
16 | This extension will perform the Code Cleanup automatically when the file is being saved.
17 |
18 | ### Configure Code Cleanup profiles
19 |
20 | At the bottom of the C# editor, click the Configure Code Cleanup.
21 |
22 | 
23 |
24 | By default, **Profile 1** is executed on save by this extension.
25 |
26 | ### Options
27 | The options page allows you to chose between which profile to run automatically on save.
28 |
29 | 
30 |
31 | ## License
32 | [Apache 2.0](LICENSE)
33 |
--------------------------------------------------------------------------------
/appveyor.yml:
--------------------------------------------------------------------------------
1 | image: Visual Studio 2019 Preview
2 |
3 | install:
4 | - ps: (new-object Net.WebClient).DownloadString("https://raw.github.com/madskristensen/ExtensionScripts/master/AppVeyor/vsix.ps1") | iex
5 |
6 | before_build:
7 | - ps: Vsix-IncrementVsixVersion | Vsix-UpdateBuildVersion
8 | - ps: Vsix-TokenReplacement src\source.extension.cs 'Version = "([0-9\\.]+)"' 'Version = "{version}"'
9 |
10 | build_script:
11 | - nuget restore -Verbosity quiet
12 | - msbuild /p:configuration=Release /p:DeployExtension=false /p:ZipPackageCompressionLevel=normal /v:m
13 |
14 | after_test:
15 | - ps: Vsix-PushArtifacts | Vsix-PublishToGallery
16 |
--------------------------------------------------------------------------------
/art/code-cleanup-menu.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/madskristensen/CodeCleanupOnSave/39616ab741f155ad1bceb5a521f5d5da89059cee/art/code-cleanup-menu.png
--------------------------------------------------------------------------------
/art/options.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/madskristensen/CodeCleanupOnSave/39616ab741f155ad1bceb5a521f5d5da89059cee/art/options.png
--------------------------------------------------------------------------------
/src/CodeCleanupOnSave.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | 16.0
5 | $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)
6 |
7 |
8 |
9 | Debug
10 | AnyCPU
11 | 2.0
12 | {82b43b9b-a64c-4715-b499-d71e9ca2bd60};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}
13 | {CBFA76B5-F552-451C-9F07-3FA6B248E0F4}
14 | Library
15 | Properties
16 | CodeCleanupOnSave
17 | CodeCleanupOnSave
18 | v4.7.2
19 | true
20 | true
21 | true
22 | true
23 | false
24 | true
25 | true
26 | Program
27 | $(DevEnvDir)devenv.exe
28 | /rootsuffix Exp
29 |
30 |
31 | true
32 | full
33 | false
34 | bin\Debug\
35 | DEBUG;TRACE
36 | prompt
37 | 4
38 |
39 |
40 | pdbonly
41 | true
42 | bin\Release\
43 | TRACE
44 | prompt
45 | 4
46 |
47 |
48 |
49 | True
50 | True
51 | VSCommandTable.vsct
52 |
53 |
54 |
55 | Component
56 |
57 |
58 |
59 |
60 |
61 |
62 |
63 |
64 | True
65 | True
66 | source.extension.vsixmanifest
67 |
68 |
69 |
70 |
71 | Resources\LICENSE
72 | true
73 |
74 |
75 | Designer
76 | VsixManifestGenerator
77 | source.extension.cs
78 |
79 |
80 |
81 |
82 |
83 |
84 |
85 |
86 |
87 |
88 |
89 |
90 |
91 |
92 | compile; build; native; contentfiles; analyzers; buildtransitive
93 |
94 |
95 | runtime; build; native; contentfiles; analyzers; buildtransitive
96 | all
97 |
98 |
99 |
100 |
101 | VsctGenerator
102 | Menus.ctmenu
103 | VSCommandTable.cs
104 |
105 |
106 | true
107 |
108 |
109 |
110 |
111 |
118 |
--------------------------------------------------------------------------------
/src/CodeCleanupOnSavePackage.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Runtime.InteropServices;
3 | using System.Threading;
4 | using Microsoft.VisualStudio.Shell;
5 | using static Microsoft.VisualStudio.VSConstants;
6 | using Task = System.Threading.Tasks.Task;
7 |
8 | namespace CodeCleanupOnSave
9 | {
10 | [PackageRegistration(UseManagedResourcesOnly = true, AllowsBackgroundLoading = true)]
11 | [InstalledProductRegistration(Vsix.Name, Vsix.Description, Vsix.Version)]
12 | [ProvideOptionPage(typeof(DialogPageProvider.General), "Environment", "Code Cleanup on Save", 0, 0, true, new[] { "Code Cleanup on Save" }, ProvidesLocalizedCategoryName = false)]
13 | [ProvideProfile(typeof(DialogPageProvider.General), "Environment", Vsix.Name, 0, 0, true)]
14 | [ProvideAutoLoad(UICONTEXT.CSharpProject_string, PackageAutoLoadFlags.BackgroundLoad)]
15 | [ProvideAutoLoad(UICONTEXT.VBProject_string, PackageAutoLoadFlags.BackgroundLoad)]
16 | [ProvideAutoLoad(UICONTEXT.FSharpProject_string, PackageAutoLoadFlags.BackgroundLoad)]
17 | [Guid(PackageGuids.guidCodeCleanupOnSavePackageString)]
18 | [ProvideMenuResource("Menus.ctmenu", 1)]
19 | public sealed class CodeCleanupOnSavePackage : AsyncPackage
20 | {
21 | protected override async Task InitializeAsync(CancellationToken cancellationToken, IProgress progress)
22 | {
23 | await JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken);
24 | await RunOnSave.InitializeAsync(this);
25 | }
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/src/Options/BaseOptionModel.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.IO;
4 | using System.Linq;
5 | using System.Reflection;
6 | using System.Runtime.Serialization.Formatters.Binary;
7 | using System.Threading.Tasks;
8 | using Microsoft;
9 | using Microsoft.VisualStudio.Settings;
10 | using Microsoft.VisualStudio.Shell;
11 | using Microsoft.VisualStudio.Shell.Interop;
12 | using Microsoft.VisualStudio.Shell.Settings;
13 | using Microsoft.VisualStudio.Threading;
14 | using Task = System.Threading.Tasks.Task;
15 |
16 | namespace CodeCleanupOnSave
17 | {
18 | ///
19 | /// A base class for specifying options
20 | ///
21 | internal abstract class BaseOptionModel where T : BaseOptionModel, new()
22 | {
23 | private static readonly AsyncLazy _liveModel = new AsyncLazy(CreateAsync, ThreadHelper.JoinableTaskFactory);
24 | private static readonly AsyncLazy _settingsManager = new AsyncLazy(GetSettingsManagerAsync, ThreadHelper.JoinableTaskFactory);
25 |
26 | protected BaseOptionModel()
27 | { }
28 |
29 | ///
30 | /// A singleton instance of the options. MUST be called from UI thread only.
31 | ///
32 | ///
33 | /// Call instead if on a background thread or in an async context on the main thread.
34 | ///
35 | public static T Instance
36 | {
37 | get
38 | {
39 | ThreadHelper.ThrowIfNotOnUIThread();
40 |
41 | #pragma warning disable VSTHRD102 // Implement internal logic asynchronously
42 | return ThreadHelper.JoinableTaskFactory.Run(GetLiveInstanceAsync);
43 | #pragma warning restore VSTHRD102 // Implement internal logic asynchronously
44 | }
45 | }
46 |
47 | ///
48 | /// Get the singleton instance of the options. Thread safe.
49 | ///
50 | public static Task GetLiveInstanceAsync() => _liveModel.GetValueAsync();
51 |
52 | ///
53 | /// Creates a new instance of the options class and loads the values from the store. For internal use only
54 | ///
55 | ///
56 | public static async Task CreateAsync()
57 | {
58 | var instance = new T();
59 | await instance.LoadAsync();
60 | return instance;
61 | }
62 |
63 | ///
64 | /// The name of the options collection as stored in the registry.
65 | ///
66 | protected virtual string CollectionName { get; } = typeof(T).FullName;
67 |
68 | ///
69 | /// Hydrates the properties from the registry.
70 | ///
71 | public virtual void Load()
72 | {
73 | #pragma warning disable VSTHRD102 // Implement internal logic asynchronously
74 | ThreadHelper.JoinableTaskFactory.Run(LoadAsync);
75 | #pragma warning restore VSTHRD102 // Implement internal logic asynchronously
76 | }
77 |
78 | ///
79 | /// Hydrates the properties from the registry asyncronously.
80 | ///
81 | public virtual async Task LoadAsync()
82 | {
83 | ShellSettingsManager manager = await _settingsManager.GetValueAsync();
84 | SettingsStore settingsStore = manager.GetReadOnlySettingsStore(SettingsScope.UserSettings);
85 |
86 | if (!settingsStore.CollectionExists(CollectionName))
87 | {
88 | return;
89 | }
90 |
91 | foreach (PropertyInfo property in GetOptionProperties())
92 | {
93 | try
94 | {
95 | string serializedProp = settingsStore.GetString(CollectionName, property.Name);
96 | object value = DeserializeValue(serializedProp, property.PropertyType);
97 | property.SetValue(this, value);
98 | }
99 | catch (Exception ex)
100 | {
101 | System.Diagnostics.Debug.Write(ex);
102 | }
103 | }
104 | }
105 |
106 | ///
107 | /// Saves the properties to the registry.
108 | ///
109 | public virtual void Save()
110 | {
111 | #pragma warning disable VSTHRD102 // Implement internal logic asynchronously
112 | ThreadHelper.JoinableTaskFactory.Run(SaveAsync);
113 | #pragma warning restore VSTHRD102 // Implement internal logic asynchronously
114 | }
115 |
116 | ///
117 | /// Saves the properties to the registry asyncronously.
118 | ///
119 | public virtual async Task SaveAsync()
120 | {
121 | ShellSettingsManager manager = await _settingsManager.GetValueAsync();
122 | WritableSettingsStore settingsStore = manager.GetWritableSettingsStore(SettingsScope.UserSettings);
123 |
124 | if (!settingsStore.CollectionExists(CollectionName))
125 | {
126 | settingsStore.CreateCollection(CollectionName);
127 | }
128 |
129 | foreach (PropertyInfo property in GetOptionProperties())
130 | {
131 | string output = SerializeValue(property.GetValue(this));
132 | settingsStore.SetString(CollectionName, property.Name, output);
133 | }
134 |
135 | T liveModel = await GetLiveInstanceAsync();
136 |
137 | if (this != liveModel)
138 | {
139 | await liveModel.LoadAsync();
140 | }
141 | }
142 |
143 | ///
144 | /// Serializes an object value to a string using the binary serializer.
145 | ///
146 | protected virtual string SerializeValue(object value)
147 | {
148 | using (var stream = new MemoryStream())
149 | {
150 | var formatter = new BinaryFormatter();
151 | formatter.Serialize(stream, value);
152 | stream.Flush();
153 | return Convert.ToBase64String(stream.ToArray());
154 | }
155 | }
156 |
157 | ///
158 | /// Deserializes a string to an object using the binary serializer.
159 | ///
160 | protected virtual object DeserializeValue(string value, Type type)
161 | {
162 | byte[] b = Convert.FromBase64String(value);
163 |
164 | using (var stream = new MemoryStream(b))
165 | {
166 | var formatter = new BinaryFormatter();
167 | return formatter.Deserialize(stream);
168 | }
169 | }
170 |
171 | private static async Task GetSettingsManagerAsync()
172 | {
173 | await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();
174 | return new ShellSettingsManager(ServiceProvider.GlobalProvider);
175 | }
176 |
177 | private IEnumerable GetOptionProperties()
178 | {
179 | return GetType()
180 | .GetProperties()
181 | .Where(p => p.PropertyType.IsSerializable && p.PropertyType.IsPublic);
182 | }
183 | }
184 | }
185 |
--------------------------------------------------------------------------------
/src/Options/BaseOptionPage.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.VisualStudio.Shell;
2 |
3 | namespace CodeCleanupOnSave
4 | {
5 | ///
6 | /// A base class for a DialogPage to show in Tools -> Options.
7 | ///
8 | internal class BaseOptionPage : DialogPage where T : BaseOptionModel, new()
9 | {
10 | private readonly BaseOptionModel _model;
11 |
12 | public BaseOptionPage()
13 | {
14 | #pragma warning disable VSTHRD102 // Implement internal logic asynchronously
15 | _model = ThreadHelper.JoinableTaskFactory.Run(BaseOptionModel.CreateAsync);
16 | #pragma warning restore VSTHRD102 // Implement internal logic asynchronously
17 | }
18 |
19 | public override object AutomationObject => _model;
20 |
21 | public override void LoadSettingsFromStorage()
22 | {
23 | _model.Load();
24 | }
25 |
26 | public override void SaveSettingsToStorage()
27 | {
28 | _model.Save();
29 | }
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/src/Options/DialogPageProvider.cs:
--------------------------------------------------------------------------------
1 | namespace CodeCleanupOnSave
2 | {
3 | ///
4 | /// A provider for custom implementations.
5 | ///
6 | internal class DialogPageProvider
7 | {
8 | public class General : BaseOptionPage { }
9 | }
10 | }
11 |
--------------------------------------------------------------------------------
/src/Options/GeneralOptions.cs:
--------------------------------------------------------------------------------
1 | using System.ComponentModel;
2 |
3 | namespace CodeCleanupOnSave
4 | {
5 | internal class GeneralOptions : BaseOptionModel
6 | {
7 | [Category("General")]
8 | [DisplayName("Enabled")]
9 | [Description("Specifies whether to run Code Clean up automatically on save or not.")]
10 | [DefaultValue(true)]
11 | public bool Enabled { get; set; } = true;
12 |
13 | [Category("General")]
14 | [DisplayName("Profile")]
15 | [Description("Specifies whether to run Code Clean up automatically on save or not.")]
16 | [DefaultValue(CodeCleanupProfile.Profile1)]
17 | [TypeConverter(typeof(EnumConverter))]
18 | public CodeCleanupProfile Profile { get; set; } = CodeCleanupProfile.Profile1;
19 |
20 | public enum CodeCleanupProfile
21 | {
22 | Profile1,
23 | Profile2
24 | }
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/src/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 | using System.Runtime.InteropServices;
3 | using CodeCleanupOnSave;
4 |
5 | [assembly: AssemblyTitle(Vsix.Name)]
6 | [assembly: AssemblyDescription(Vsix.Description)]
7 | [assembly: AssemblyConfiguration("")]
8 | [assembly: AssemblyCompany(Vsix.Author)]
9 | [assembly: AssemblyProduct(Vsix.Name)]
10 | [assembly: AssemblyCopyright(Vsix.Author)]
11 | [assembly: AssemblyTrademark("")]
12 | [assembly: AssemblyCulture("")]
13 |
14 | [assembly: ComVisible(false)]
15 |
16 | [assembly: AssemblyVersion(Vsix.Version)]
17 | [assembly: AssemblyFileVersion(Vsix.Version)]
18 |
--------------------------------------------------------------------------------
/src/Resources/Icon.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/madskristensen/CodeCleanupOnSave/39616ab741f155ad1bceb5a521f5d5da89059cee/src/Resources/Icon.png
--------------------------------------------------------------------------------
/src/RunOnSave.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.ComponentModel.Design;
3 | using Microsoft;
4 | using Microsoft.VisualStudio.Shell;
5 | using Task = System.Threading.Tasks.Task;
6 |
7 | namespace CodeCleanupOnSave
8 | {
9 | internal sealed class RunOnSave
10 | {
11 | public static async Task InitializeAsync(AsyncPackage package)
12 | {
13 | await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(package.DisposalToken);
14 |
15 | var commandService = await package.GetServiceAsync(typeof(IMenuCommandService)) as OleMenuCommandService;
16 | Assumes.Present(commandService);
17 |
18 | var menuCommandID = new CommandID(PackageGuids.guidCodeCleanupOnSavePackageCmdSet, PackageIds.RunOnSave);
19 | var menuItem = new OleMenuCommand(Execute, menuCommandID);
20 | menuItem.BeforeQueryStatus += MenuItem_BeforeQueryStatus;
21 | commandService.AddCommand(menuItem);
22 | }
23 |
24 | private static void MenuItem_BeforeQueryStatus(object sender, EventArgs e)
25 | {
26 | var button = (OleMenuCommand)sender;
27 |
28 | button.Checked = GeneralOptions.Instance.Enabled;
29 | }
30 |
31 | private static void Execute(object sender, EventArgs e)
32 | {
33 | var button = (OleMenuCommand)sender;
34 |
35 | GeneralOptions.Instance.Enabled = !button.Checked;
36 | GeneralOptions.Instance.Save();
37 | }
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/src/SaveHandler.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.ComponentModel.Composition;
3 | using EnvDTE;
4 | using EnvDTE80;
5 | using Microsoft.VisualStudio.Commanding;
6 | using Microsoft.VisualStudio.Shell;
7 | using Microsoft.VisualStudio.Text;
8 | using Microsoft.VisualStudio.Text.Editor;
9 | using Microsoft.VisualStudio.Text.Editor.Commanding;
10 | using Microsoft.VisualStudio.Text.Editor.Commanding.Commands;
11 | using Microsoft.VisualStudio.Utilities;
12 |
13 | namespace CodeCleanupOnSave
14 | {
15 | [Export(typeof(ICommandHandler))]
16 | [Name(nameof(SaveHandler))]
17 | [ContentType("csharp")]
18 | [ContentType("basic")]
19 | [ContentType("f#")]
20 | [TextViewRole(PredefinedTextViewRoles.PrimaryDocument)]
21 | public class SaveHandler : ICommandHandler
22 | {
23 | public string DisplayName => nameof(SaveHandler);
24 |
25 | private readonly IEditorCommandHandlerServiceFactory _commandService;
26 |
27 | [ImportingConstructor]
28 | public SaveHandler(IEditorCommandHandlerServiceFactory commandService)
29 | {
30 | _commandService = commandService;
31 | }
32 |
33 | public bool ExecuteCommand(SaveCommandArgs args, CommandExecutionContext executionContext)
34 | {
35 | ThreadHelper.ThrowIfNotOnUIThread();
36 |
37 | // Check if file is part of a project first.
38 | if (args.SubjectBuffer.Properties.TryGetProperty(typeof(ITextDocument), out ITextDocument textDoc))
39 | {
40 | var filePath = textDoc.FilePath;
41 |
42 | var dte = Package.GetGlobalService(typeof(DTE)) as DTE2;
43 | ProjectItem item = dte.Solution?.FindProjectItem(filePath);
44 |
45 | if (string.IsNullOrEmpty(item?.ContainingProject?.FullName))
46 | {
47 | return true;
48 | }
49 | }
50 |
51 | // Then check if it's been enabled in the options.
52 | if (!GeneralOptions.Instance.Enabled)
53 | {
54 | return true;
55 | }
56 |
57 | try
58 | {
59 | IEditorCommandHandlerService service = _commandService.GetService(args.TextView);
60 |
61 | // Profile 1
62 | if (GeneralOptions.Instance.Profile == GeneralOptions.CodeCleanupProfile.Profile1)
63 | {
64 | var cmd = new CodeCleanUpDefaultProfileCommandArgs(args.TextView, args.SubjectBuffer);
65 | service.Execute((v, b) => cmd, null);
66 | }
67 | // Profile 2
68 | else if (GeneralOptions.Instance.Profile == GeneralOptions.CodeCleanupProfile.Profile2)
69 | {
70 | var cmd = new CodeCleanUpCustomProfileCommandArgs(args.TextView, args.SubjectBuffer);
71 | service.Execute((v, b) => cmd, null);
72 | }
73 | }
74 | catch (Exception ex)
75 | {
76 | System.Diagnostics.Debug.WriteLine(ex);
77 | }
78 |
79 | return true;
80 | }
81 |
82 | public CommandState GetCommandState(SaveCommandArgs args)
83 | {
84 | return CommandState.Available;
85 | }
86 |
87 | }
88 | }
89 |
--------------------------------------------------------------------------------
/src/VSCommandTable.cs:
--------------------------------------------------------------------------------
1 | // ------------------------------------------------------------------------------
2 | //
3 | // This file was generated by VSIX Synchronizer
4 | //
5 | // ------------------------------------------------------------------------------
6 | namespace CodeCleanupOnSave
7 | {
8 | using System;
9 |
10 | ///
11 | /// Helper class that exposes all GUIDs used across VS Package.
12 | ///
13 | internal sealed partial class PackageGuids
14 | {
15 | public const string guidCodeCleanupOnSavePackageString = "aee4d337-3c9a-4f9b-86ae-6dd7bd751bd5";
16 | public static Guid guidCodeCleanupOnSavePackage = new Guid(guidCodeCleanupOnSavePackageString);
17 |
18 | public const string guidValidFileString = "e53facf8-0840-4d99-bd57-fafcb7de25e4";
19 | public static Guid guidValidFile = new Guid(guidValidFileString);
20 |
21 | public const string guidCodeCleanupOnSavePackageCmdSetString = "d8b9208d-7e71-4fbe-9c53-6950c7c5679b";
22 | public static Guid guidCodeCleanupOnSavePackageCmdSet = new Guid(guidCodeCleanupOnSavePackageCmdSetString);
23 |
24 | public const string guidEditorCommandsString = "160961b3-909d-4b28-9353-a1bef587b4a6";
25 | public static Guid guidEditorCommands = new Guid(guidEditorCommandsString);
26 | }
27 | ///
28 | /// Helper class that encapsulates all CommandIDs uses across VS Package.
29 | ///
30 | internal sealed partial class PackageIds
31 | {
32 | public const int RunOnSave = 0x0100;
33 | public const int IDG_CTX_CODECLEANUP_PROFILES = 0x0025;
34 | }
35 | }
--------------------------------------------------------------------------------
/src/VSCommandTable.vsct:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
--------------------------------------------------------------------------------
/src/source.extension.cs:
--------------------------------------------------------------------------------
1 | // ------------------------------------------------------------------------------
2 | //
3 | // This file was generated by VSIX Synchronizer
4 | //
5 | // ------------------------------------------------------------------------------
6 | namespace CodeCleanupOnSave
7 | {
8 | internal sealed partial class Vsix
9 | {
10 | public const string Id = "66985471-b701-4851-a2d7-5a8bdce1e694";
11 | public const string Name = "Code Cleanup On Save";
12 | public const string Description = @"Automatically run one of the Code Clean profiles when saving the document. This ensures your code is always formatted correctly and follows your coding style conventions.";
13 | public const string Language = "en-US";
14 | public const string Version = "1.0.999";
15 | public const string Author = "Mads Kristensen";
16 | public const string Tags = "cleanup, formatting";
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/src/source.extension.vsixmanifest:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Code Cleanup On Save
6 | Automatically run one of the Code Clean profiles when saving the document. This ensures your code is always formatted correctly and follows your coding style conventions.
7 | https://github.com/madskristensen/CodeCleanupOnSave
8 | Resources\LICENSE
9 | Resources\Icon.png
10 | Resources\Icon.png
11 | cleanup, formatting
12 |
13 |
14 |
15 |
18 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
--------------------------------------------------------------------------------