Geert Van Laethem
Geert Van Laethem

Reputation: 737

Writing Visual Studio settings in an extension do not stay

In my extension that I am writing for Visual Studio 2015 I want to change the tab size and indent size as at work we have a different setting as when I am developing for opensource project (company history dating our C period). I have written the following code in my command class:

private const string CollectionPath = @"Text Editor\CSharp";
private void MenuItemCallback(object sender, EventArgs e)
{
  var settingsManager = new ShellSettingsManager(ServiceProvider);
  var settingsStore = settingsManager.GetWritableSettingsStore(SettingsScope.UserSettings);
  var tabSize = settingsStore.GetInt32(CollectionPath, "Tab Size", -1);
  var indentSize = settingsStore.GetInt32(CollectionPath, "Indent Size", -1);
  if (tabSize != -1 && indentSize != -1)
  {
    settingsStore.SetInt32(CollectionPath, "Tab Size", 2);
    settingsStore.SetInt32(CollectionPath, "Indent Size", 2);
  }
}

When testing in an experimental hive it changes it when you step through the method but when you open the Options dialog it stays the original values. When you debug again the values stay the original.

What did I forget or did wrong?

Upvotes: 6

Views: 436

Answers (2)

Geert Van Laethem
Geert Van Laethem

Reputation: 737

To be complete. This is the correct answer:

In the constructor you need to add

_dte2 = (DTE2) ServiceProvider.GetService(typeof (DTE));

And with the command it is like this

    _dte2.Properties["TextEditor", "CSharp"].Item("TabSize").Value = 2;
    _dte2.Properties["TextEditor", "CSharp"].Item("IndentSize").Value = 2;
    _dte2.Commands.Raise(VSConstants.CMDSETID.StandardCommandSet2K_string, (int)VSConstants.VSStd2KCmdID.FORMATDOCUMENT, null, null);

There is an issue that the changed options are overridden with the defaults when you restart Visual Studio.

Upvotes: 1

NineBerry
NineBerry

Reputation: 28539

Directly access the Visual Studio options via the Properties functionality in the EnvDTE assembly.

private void ChangeTabs(DTE vs, int newTabSize, int newIndentSize)
{
    var cSharp = vs.Properties["TextEditor", "CSharp"];

    EnvDTE.Property lTabSize = cSharp.Item("TabSize");
    EnvDTE.Property lIndentSize = cSharp.Item("IndentSize");

    lTabSize.Value = newTabSize;
    lIndentSize.Value = newIndentSize;
}

private void ChangeSettings()
{
   DTE vs = (DTE)GetService(typeof(DTE)); 
   ChangeTabs(vs, 3, 3);
}

For reference: Controlling Options Settings

Upvotes: 4

Related Questions