I'm trying to convert a Web Site (web forms) to a Web Application (also web forms). I've converted all files via "Convert to Web Application" from Visual Studio; this created a bunch of designer.cs files.
From what I understand these files contain code that is extracted from the main .cs file to avoid developers tempering with it; and to make it work the classes in both the .cs file and the .designer.cs file are declared partial.
Unfortunately when developing .aspx pages, the code behind class was often named randomly (often times just "Page") and now I find a whole lot of compilation errors that find conflicting names between all these different pages partial class.
Is there any way to regenerate these class names to something appropriate so that they don't conflict with each other? Even just something based on the path to the file would be enough.
I wrote a Python script that does that. If anybody needs that, here it is:
import fnmatch
import os
import re
def get_all_aspx_files(dir):
aspx_files = []
for root, dirnames, filenames in os.walk(dir):
for filename in fnmatch.filter(filenames, '*.aspx'):
aspx_files.append(os.path.join(root, filename))
return aspx_files
def generate_class_name(file):
class_name = file\
.replace('./', '')\
.replace('/', '_')\
.replace('-', '_')\
.replace('.aspx', '')
return class_name
def inplace_regex_replace(filename, pattern, replace):
with open(filename) as f:
s = f.read()
with open(filename, 'w') as f:
s = re.sub(pattern, replace, s)
f.write(s)
aspx_files = get_all_aspx_files('.')
for file in aspx_files:
cs_file = file + '.cs'
designer_cs_file = file + '.designer.cs'
class_name = generate_class_name(file)
inplace_regex_replace(file, 'Inherits="[A-Za-z0-9_]+"', 'Inherits="%s"' % class_name)
inplace_regex_replace(cs_file, 'public partial class [A-Za-z0-9_]+', 'public partial class %s' % class_name)
try:
inplace_regex_replace(designer_cs_file, 'public partial class [A-Za-z0-9_]+', 'public partial class %s' % class_name)
except IOError as e:
print e
You just need to place it at the root of your project and then run it with:
python script.py