Wednesday, March 16, 2011

Add a common namespace reference by default to all pages in a project

Is there any easy way to add a using statement to every class I create in a project without having to write

using SomeNamespace;

in every file?

[edit] I could add a template I realise but I'm talking about doing it for every file in an existing project.

From stackoverflow
  • I believe you can do something like:

    <system.web>
            <pages>
                  <namespaces>
                        <add namespace="System.IO" />
                        <add namespace="System.Text"/>
                        <add namespace="Westwind.Tools"/>
                  </namespaces>
            </pages>
    </system.web>
    

    http://www.west-wind.com/WebLog/posts/2287.aspx

    marshall : Thanks but this only works for aspx pages. I'm more interested in .cs files in this case.
    EndangeredMassa : I wasn't sure if this would apply to the code or not. I've not actually used it.
  • Go to "My Project" > "References" tab > "Imported Namespaces" section. Check any namespaces that you want available on every page.

    marshall : My Project sounds like a vb thing. Will try and find a C# equiv and try this. Thanks
    EndangeredMassa : Yeah, I use VB. C# Should have similar settings somewhere. Try finding project properties somewhere.
  • Note the web.config settings only work for code inside of page markup not in CodeFile/CodeBehind pages, so that's not really a solution.

    Another way to do this is to create an empty page with just the right setup you want - namespaces, plus possibly a common base class etc. and then create a page template from that.

    Check out File | Export Template...

    It's extremely easy and lets you create exactly what you need. Works for most file types as well as entire projects that can be templatized (is that a word? :-})...

    marshall : Template is a great solution going forward but I'm looking for something to retrofit over existing code. Thanks rick
  • A find/replace across your project of "using System;" with "using System; using SomeNamespace;" will get you most of the way there quickly.

0 comments:

Post a Comment