Change DebugType in multiple C# projects.rb

Change DebugType in multiple C# projects.rb

To change settings of multiple C# projects is quite easy with Ruby and the Nokogiri gem. The following script will change the DebugType of all Release configurations in multiple csproj files.

#encoding: utf-8
require 'Nokogiri'

desc "Change the DebugType of a configuration in multiple C# project files."
task :change_debug_type do
    DEBUG_TYPE = 'pdbonly'
    CONFIGURATION = 'Release'
    PROJECT_DIR_REL = '../Source/**/*'

    project_files(PROJECT_DIR_REL).each do |file_name|
        change(file_name, CONFIGURATION, DEBUG_TYPE)
    end
end

def project_files(project_dir_rel)
    scriptDir = File.dirname(__FILE__)
    Dir[ File.join(scriptDir, "#{project_dir_rel}/*.csproj")]
end

def change(file_name, configuration, debug_type)
    puts '-------------------------------------------------------------------------------'
    puts file_name
    puts '-------------------------------------------------------------------------------'
    puts

    @doc = Nokogiri::XML(File.open(file_name))
    namespace = "http://schemas.microsoft.com/developer/msbuild/2003"
    nodes =@doc.xpath("//x:PropertyGroup","x" => namespace)

    nodes.each do |node|   
        if node.values.to_s.include? configuration
            puts node.values
            type_node = node.at_xpath("x:DebugType", "x" => namespace)
            if type_node == nil
                new_node = Nokogiri::XML::Node.new("DebugType", @doc)
                new_node.content = debug_type
                node.add_child(new_node)
                puts "Created new node: #{new_node}"
            else     
                puts type_node
                puts "Change #{type_node.content} to #{debug_type}"
                type_node.content = debug_type
            end
            puts
        end 
    end

    File.open(file_name, 'w') {|f| f.puts @doc.to_xml }
    puts  '-------------------------------------------------------------------------------'
    puts
end


task :default  => [:change_debug_type]

[Code on gist]

At first the script gets all csproj files which are actually xml files. Each file is loaded into a doc variable by using Nokogiri. Then the document is queried with XPath for the PropertyGroup tags. Each tag is validated if it matches the specified configuration. If it matches a query for the DebugType tag is executed. If it isn't found a new DebugType node with the specified DebugType value is created. Otherwise the available tag is changed. Finally the modified XML is written into the original project file.


Cover photo by Robert Couse-Baker / CC (BY)